Before we jump straight into this article, for you to follow along you must have a good understanding of what components in react are and some basic understanding of Javascript.
In this article we will be explaining what props are and how they are used in react and then we will dive into react code to see how props works and how they are used to share values between components.
Note: Props can only be passed from a parent component to a child components as react has a unidirectional data flow.
Props is a short form for properties, it is a way of sharing values between components or to put it in a shorter way it is an argument passed into a component, with the use of props we are able to to pass data from a parent component to a child component.
Now let’s take a look at how components share props and what problems they solve now that we know what they are;
function Button() {
return (
<button>Click here</button>
)
}
function App() {
return (<>
<Button />
<Button />
</>
)
}
In the code above we can observe see that we have two button components rendered in the app component which will show the following in the browser
As you can see the two buttons show the same thing but you might ask what if we want these buttons to show different values or lets just say for example we want the second button to display don't click me, this is where props comes in handy to get over this obstacle, now we will create a props in the child component "Button" called text and use it as a variable in each button component rendered inside the app component;
function Button({text}) {
return (
<button>{text}</button>
)
}
function App() {
return (<>
<Button text="click me" />
<Button text="Dont click me" />
</>
)
}
Now with this we have successfully changed the text values in the two different button components thereby overcoming the obstacle we talked about above, this code will show the following in the browser
Now this is not all we can do with props, we can also utilize the power of props to apply different styles across the two buttons;
function Button({text, color, backgroundColor}) {
const btnstyle ={
color: color,
backgroundColor: backgroundColor
}
return (
<button style={btnstyle}>{text}</button>
)
}
function App() {
return (<>
<Button text="click me" color="white" backgroundColor="blue" />
<Button text="Dont click me" color="green" backgroundColor="black" />
</>
)
}
In the code snippet above we are able to pass values in objects as props as we could change the style of the button using the properties in "btnStyle" object. The result of our code snippet is shown below.
Conclusion
With this knowledge given to you above you should be able to pass props between components and lessen the code you have to write.
For more Information on props and how they work:https://react.dev/learn/passing-props-to-a-component
Top comments (1)
Well done!