Created
April 3, 2019 09:30
-
-
Save iest/8b2f9358851ac35c213e15556ae6efc0 to your computer and use it in GitHub Desktop.
react context string-adder
This file contains hidden or 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
// @flow | |
import * as React from 'react'; | |
import * as R from 'ramda'; | |
const SEPARATOR = '.'; | |
const spaceToHyphen = R.replace(/\s/g, '-'); | |
const delimit = (str, add) => | |
R.compose( | |
R.join(SEPARATOR), | |
R.map( | |
R.compose( | |
spaceToHyphen, | |
R.trim, | |
R.toLower | |
) | |
), | |
R.filter(Boolean), | |
R.append(add), | |
R.split(SEPARATOR) | |
)(str); | |
const STRContext = React.createContext({ name: '' }); | |
export const STRName = ({ name: lastName, children }) => ( | |
<STRContext.Consumer> | |
{({ name }) => <STRContext.Provider value={{ name: delimit(name, lastName) }}>{children}</STRContext.Provider>} | |
</STRContext.Consumer> | |
); | |
class STRPropsComponent extends React.Component { | |
DEBUG = false; | |
constructor(props) { | |
super(props); | |
if (this.DEBUG) { | |
this.startDebugTimer(); | |
} | |
} | |
componentWillUnmount() { | |
this.cancelDebugTimer(); | |
} | |
state = { error: false }; | |
debugTimer = null; | |
startDebugTimer = () => { | |
this.debugTimer = setTimeout(() => this.setState({ error: true }), 5000); | |
}; | |
cancelDebugTimer = () => this.debugTimer && clearTimeout(this.debugTimer); | |
render() { | |
const { name: lastName, children } = this.props; | |
const childProps = {}; | |
if (this.DEBUG) { | |
childProps.onLayout = this.cancelDebugTimer; | |
} | |
return ( | |
<STRContext.Consumer> | |
{({ name }) => | |
children({ | |
...childProps, | |
dataSTR: delimit(name, lastName), | |
}) | |
} | |
</STRContext.Consumer> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment