DEV Community

katongole Isaac
katongole Isaac

Posted on

React reusable components

Image description

When creating components, its better to fully optimize reactjs library for its use ( re-usability ).

Here are some key concepts to achieve resuability

  • Generalize your components

    Create components that are loosely coupled from the concept you are trying to achieve. for example when creating a form, its better to create one input component that serves many purposes. i.e

const Input = ({  name, value , onChange, ...rest } ) => {
    return <input 
        name={name}
        onChange={ e => onChange(e)}
        value={value}
        {...rest}
    />
}
Enter fullscreen mode Exit fullscreen mode
  • Raise events and don't pass handlers directly.

    Its better for a component to determine how it deals its data given either via props or state. To maintain and achieve re-usability, its better to avoid passing down handlers but raise events.

With this line of code, onChange= {e => onChange(e)} the consumer of the Input Component can pass whatever kind of handler he/she wants therefore giving you more freedom on your code.

Top comments (0)