React reusable components
katongole Isaac
Posted on May 19, 2023
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}
/>
}
-
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.
Posted on May 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 15, 2024