Last active
November 8, 2017 04:44
-
-
Save export-mike/f03fc23c06ef108099fc6e5d7b700827 to your computer and use it in GitHub Desktop.
react-plural
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
export default props => { | |
const messageBuilt = plural(props); | |
return <span>{messageBuilt}</span>; | |
}; | |
export const plural = ({ message, ...rest }) => { | |
const messageBuilt = Object.keys(rest).reduce((messageTemplate, key) => { | |
if (!Array.isArray(rest[key])) { | |
if (typeof rest[key] === 'number') { | |
return messageTemplate | |
.replace(new RegExp(`{${key}}`, 'g'), rest[key]) | |
.replace( | |
new RegExp(`{${key.replace(/Count/g, '')}Plural}`, 'g'), | |
rest[key] > 1 ? 's' : '' | |
); | |
} | |
return messageTemplate; | |
} | |
return messageTemplate | |
.replace(new RegExp(`{${key}Count}`, 'g'), rest[key].length) | |
.replace( | |
new RegExp(`{${key}Plural}`, 'g'), | |
rest[key].length > 1 ? 's' : '' | |
); | |
}, message); | |
return messageBuilt; | |
}; |
<Plural friendsCount={2} message="You have {friendsCount} friend{friendsPlural}" />
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
<Plural friends={['1','2']} message="You have {friendsCount} friend{friendsPlural}" />
You have 2 friends