React patterns
by Kostiantyn Synyshyn
Front-end Developer at Levi Nine

Table of contents

React component patterns (structural)

Hooks patterns

 

Render props

const SampleComponent = ({children}) => <div>{children('DATA_SAMPLE')}</div>
 - component calls children as a function, passing data, or exposing the render function

Proxy component

 - 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>)
    
}

Layout component

 - 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 inputs

 - 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}/>
  )
  
}

Compound components

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

Screw it & replace it all w hooks

Summary

Thank you!

Q&A

React patterns

By Kostiantyn Synyshyn

React patterns

Introduction Lecture

  • 40