React Components

jinwu

Jin Wu

Posted on March 19, 2020

React Components

Alt Text

Before we begin, it's important to know that the parent components are able to send down properties to it's children component(s).

Alt Text

The simplest way to create a component of React is to use functional components. Functional components are just regular functions in JavaScript.

Alt Text

Above are examples of writing a functional component. One is a regular function and the other is an arrow function. When using a functional component, you have to pass in an argument in order to get access to the properties you want to receive from the parent. In my examples, I used props as the argument.

Now lets move onto a slightly more complex way of creating a React component via the class component.

Alt Text

The example shown above will return the same results as the functional component examples. Some of the differences between the two is that class components are more complex under the hood and you don't need to pass in an argument to gain access to the parents properties. You can just call this.props.name to get the return value.

  • In functional components, the argument can be anything. But in class components, you have to use props.

Alt Text

One very important difference between functional and class components is the ability to use state. Functional components are just basic functions of JavaScript and doesn't have it's own state. Class components on the other hand does. State will be very important when you want to update something in your React app.

Props are read-only. If you want to be able to update information on your component, I suggest you use a class component. Of course, there are ways around it by lifting the state up to the parent component and then pass it down to the functional component via props. The parent component will most likely be a class component to gain access to state.

The React docs are a great resource if you want to learn more about state, lifting state, and inverse data flow.

React Documentation

đź’– đź’Ş đź™… đźš©
jinwu
Jin Wu

Posted on March 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related