Kostiantyn Synyshyn
JS engineer
React patterns
by Kostiantyn Synyshyn Front-end Developer at Levi Nine
React component patterns (structural)
Hooks patterns
const SampleComponent = ({children}) => <div>{children('DATA_SAMPLE')}</div>
- component calls children as a function, passing data, or exposing the render function
- component proxies props to a lower-level component
const ProjectSpecificButton = ({onClick, children}) => {
const buttonClickHandler = (event) => {
collectAnalyticsData()
onChange.?(event.target.value)
}
return (<Button onClick={buttonClickHandler}>{children}</Button>)
}
- component, that doesn't change frequently, represents the common structure on the site
const App = () => (
<Layout
header={<Heading />}
footer={<Footer/>}>
<Page/>
</Layout>
)
// Layout component possible implementation
const Layout = ({header, footer, children, ...props}) => {
return (
<>
<header>{header}</header>
<main>
<StyledGrid>{children}</StyledGrid>
</main>
<footer>{footer}</footer>
</>
)
}
- controlled input disallows DOM elements to run mutations, .etc via the native API - everything is now controlled by React & JS
// in your HTML common input usage
<form>
<input type="email"/>
<input type="password"/>
<input type="submit">Submit my creds!</input>
</form>
// Controlled inpit w JSX
const MyCustomComponent = () => {
const [inputText, setInputState] = useState('')
const inputChangeHandler = (event) => {
setInputState(event.target.value)
}
return (
<input type="text" onChange={inputChangeHandler}/>
)
}
use at your own risk
const SomewhereOnYourPage = () => {
const { Modal, isModalOpen, openModalHandler, closeModalHandler, modalProps} = useModal()
return (
<div>
<button
onClick={isModalOpen ? closeModalHandler : openModalHandler}>
{isModalOpen ? "Close" : "Open"}
</button>
<Modal {...modalProps}/>
</div>
)
}
- return component and its props from the hook
Thank you!
Q&A
By Kostiantyn Synyshyn
Introduction Lecture