Day 5: Props in React
A lesson on props in React
In the last lesson, we studied how to simply display a welcome message. Nevertheless, real-world applications are more complex than just displaying a message. To deal with this, we use props in React. Props mean properties. And if you have learned Python, you can say props are like arguments to a function. They will be passing around to make the program takes some kind of input either from other parts of the program or from the user.
Open the App.js file and add the following code.
import './App.css';import React from 'react';import Welcome from './components/welcome';function App() { return ( <div className="App"> <Welcome name ="John"/> </div>);}export default App;
line 1: we are importing our Welcome function
line 2: This is similar to what we did in the last lesson, just we have this new name=” John” added after the Welcome tag. We are passing property to our function with the name being specified.
line 3: exporting the App
let’s see what changes we need to do in the Welcome.js file
import React from 'react';function Welcome(props){return <h1>hey {props.name}!!</h1>}export default Welcome
line 1: importing React
line 2: our function is the same as before, just we added this {props.name} in our h1 tag. what it does is actually taking that property we defined in our App.js file and showing it over here. One other thing is our Welcome function taking these props as input. So, you have to carefully understand how data is flowing in the app right now.
line 3: exporting the Welcome
and you can see the output of the program.
So, that’s it for today. Thank you!