React Props for Beginners in 2021
Reusing Components is quite easy for a beginner but using props i.e configuring props it can prove to be quite a headache. That's why I came up with this article to make your learning easier. As attributes are to HTML elements so are props to components though serving differently. Props are used to pass data between React components.
🌟 It begins by adding attributes where you have used your component (App.js). In our case we add attributes to where the Car component is used. The attributes I add will be brand and year. Brand representing the vehicles brand and year the first time the brand was manufactured. (brand="lorem"
and year="20##"
)
import './App.css';
import Car from "./Car/Car"
const App = () => {
return (
<div className="App">
<h1>Hi, I'm a react App</h1>
<p>This is really working!</p>
<Car brand="Junsa" year="2019" />
<Car brand="Apple Car" year="2021" />
<Car brand="Tesla" year="2020" />
</div>
);
}
export default App;
🌟 We then move on to destructure our props which will named just like the attributes we added to our used components. We add {brand, year}
to the first line where we declare our component. (Car.js). Since we want the paragraph to be dynamic according to the props we enclose the prop names in calri braces in our case {brand}
and year
.
const Car = ({brand, year}) => {
return(
<>
<p>The {brand} vehicle brand was first manufactured in the year {year}.</p>
</>
);
}
export default Car;
💫Thats how easy it should be to understand props in react. Thankyou.