This article will show you how you can create more reusable and readable components in React by sticking to just a few simple rules.
I believe that the best way to learn is by example, so we’re gonna rely on a simple application that displays cars from API in a different way.
Application available here :
Ok, let’s start cooking!
In order to prepare a delicious dish we have to stick to the recipe, which includes:
Our starting point will be CarsList
component onmain
branch from this reusable-components repository.
import React, { useState, useEffect } from 'react';
const CarsList = () => {
const [cars, setCars] = useState([]);
useEffect(() => {
const fetchCars = async () => {
const response = await fetch('http://localhost:4000/cars');
setCars(await response.json())
}
fetchCars();
}, [])
return (
<div>
{cars.map((car, index) => <li key={index}>[{++index}]{car.name} - {car.price}$</li>)}
</div>
)
}
export default CarsList;
#javascript #react #react-hook #reactjs