DEV Community

loading...
Cover image for Anatomy of a reusable component in React

Anatomy of a reusable component in React

jesuscovam profile image jesuscovam Updated on ・2 min read

Hi there, I'm going to explain you how to decompose into peaces a component, like the one I'm using right now.

maincp

The component will have several selects, the goal is to use the same select component with different parameters, so we actually do ourselves the favor of not having to write the same test more than once and reduce our codebase.

Imports

imports

Imports at the first lines of every js file is a thumb rule, I've seen people using dinamic imports but... well I haven't have the use case for now. So we'll write them at the beginning.

Component Declaration

component declaration
Here is where the composition begins.

Declaration

we declare the component as a function or a const, I prefer const so I have my chance of a 1 line declaration with return.

Parameters

the parameters inside the ({ }) have general names, that's because we plan to use this component for different types of data that fit the description. This case is the already selected names of descriptive items that create a new pool in the database.

Logic

logic
This function "useFetchData" will fetch some data from the database (in my case is firestore). And will update the state, from this state we can part to the UI section of this component.

Return (UI)

return statement
This is it, here's were we actually serve some UI to the app. We'll use some already written/tested components from @material-ui, which gets really mad if you don't control a form component, so we are going to use the controlledValue state and onChange method written in the component declaration.

< Select >some some < /Select >

select
The select tag will display in a dropdown style N options we write inside them, as we are using react and plan to make this component reusable, we are going to display the options from the recently updated state that fit the collection written in the composition of this component.

That's it

We did it, we wrote a reusable component in React.

Full Component

component

First Picture

multiples uses of component

Thanks for your time!

If you want to chat about javascript || apps, please, feel free to write me a message✌️

Jesus Cova
Full Stack Developer
jesusc.dev
twitter

Discussion (0)

pic
Editor guide