Hi there, I'm going to explain you how to decompose into peaces a component, like the one I'm using right now.
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 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
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
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)
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 >
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
First Picture
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
Top comments (0)