Different Ways to Create Components in React

Image for post
Image for post

As they say, there is more than one way to skin a cat. As it happens there is also more than one way to create a React component, which is much more animal friendly!

I keep coming back to React for my projects, especially now I am using Gatsby for my blog. When I do I have to try and remember all the different ways you can create components in react.

Hopefully, this page will help as a reference for you for the different ways to create a React component.

Functional components

The simplest way to create a component in React is with a simple function.

Of course with the wonders of ES6, we can just write this as an arrow function.

These are used like this:

Adding properties to functional components

You can also add properties to these simple components as well. After all, they are just javascript functions:

With functions, you can also destructure the properties in the function signature, save you having to write props over and over again.

Class components

As we did with the App above we can also create components as classes as well. If you want your component to have local state then you need to have a class component.

There are also other advantages to classes such as being to use lifecycle hooks and event handlers.

Adding Children into React Components

In many cases, you are going to want to nest components. We can do this using children in React. This is done with the special children property.

Final Thoughts

Hopefully, this page will be a useful go-to for you when you come to create your next React project. If you found this useful please share it.

There are also many ways to style react components as well, you can learn more in my next post.

Originally published at https://www.alexhyett.com on November 10, 2020.

Written by

Software Developer @ https://www.alexhyett.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store