Stateless Functional Components in React

Linked Projects:

Calreact
 

Lesson links:

Lesson code - https://github.com/learnetto/calreact/tree/lesson-4.4

The next thing we'll cover cover in this module is Stateless Functional Components.

As the name suggests, these are components which don’t handle state and can be simply defined as functions which return some JSX. They accept props as their first argument.

So when we have a component which only has a render method returning JSX, we can write it as a stateless functional component.

Our Appointment component can be written as one such component. 
 The Appointment component just renders a simple bit of UI


Because it doesn’t have any state and it just has a render function which returns a bit of UI, we can define it as a stateless function.

We’ll change it from a class to a constant and then define it as an arrow function which takes props as an argument. We don't need to specify a render function because it will simply return JSX by default. 

We can also replace this.props with props (without this.).

Appointment component rewritten as a stateless functional component


Another thing we can do is what is called as object destructuring in ES6.

We can replace props with the names of its properties inside curly braces - {appointment} .

Object destructuring of props into {appointment}

This tells the function that the incoming argument props has an appointment property on it.

And so inside the function we can directly use appointments instead of props.appointments.

Before moving on, test the app in the browser to create an appointment and make sure it still works.

Now let’s do the same with the AppointmentsList component. 
AppointmentsList component only has a render function


Because this too just has a render function, we can convert it into a stateless functional component.

Again, we'll use an arrow function with the props destructured into {appointments} and change this.props.appointments inside the function to appointments.
AppointmentsList component rewritten as a stateless functional component


In fact, because we’re using an arrow function, we don’t even need to explicitly use return. We can simplify our components even further by writing the JSX without calling return.

Look ma, no return!
No need for return

Finally, we'll test our app again and make sure it still works.

So that’s Stateless Functional Components.




Liked this tutorial? Get more like this in your inbox