Let's say you want to create a component in React, like a button. There are a few great tips I want you to keep in mind, that would help you write cleaner code for your React components and give you that senior dev feel🌚
If that sounds great, lets hop in!
1. Using TypeScript (TSX)
If you are not using TSX by now, you're wrong fr.
Except if you *just* started your React journey, it's completely understandable. If not, then I have no words😐. Do yourself a favour and pick up TypeScript. I'll be releasing a React with TypeScript post soon for that
2. Defining Interfaces correctly for your props
Let's say we were creating an input component, using regular HTML input. We could define an interface to show what props the component would receive. For example, the interface below is receiving props for our Input Component.
This code isn't very flexible, if we needed to add more props like disabled
or required
. We would need to add them into the interface, increasing how much we'd have to write into the interface. I know some of you like typing a lot, but your typing is bad in this case💀.
Since our component is based on the HTML input, we could use the React.HTMLProps
to simplify our work and make out code look a lot cleaner.
We could go further to make our component, this looks very satisfying to look at. I mean look at how those props are spread so cleanly😮💨.
3. Using defaultProps
Sometimes you want some of your props to have a default value in case you didn't supply a value into them. For example, you create a button component with width and height as props.
Here the width and the height would be optional, so using the ternary operator we could specify that if the width and height are undefined, they would have values of 200px and 50px respectively. There's one word to describe this approach. INELEGANT.
Let's try something else
Using the nullish coalescing operator, we could make this look better. Just like in the previous code, if the width and height are not defined via props, they would have values of 200px and 50px respectively.
But come on, you can do better than that. You are a senior dev in the making🌚. Let's try an even better approach.
Using the defaultProps
object, we can define default values for our props in case they are not defined. Now doesn't this look clean👀. And it works for both JSX and TSX.
That's all for this week, if you like helpful tips like this don't forget to like this article and comment. You can also follow me on Twitter and subscribe to my blog for more content like this.
Until next time, byeeeee