The Questions and the Rules to Props
Adriana DiPietro
Posted on July 29, 2021
The Questions
What is Props?
Props represents data. Props allow a component to receive data from its parent component.
Why do we use Props?
We use Props because React is a component-based library. React separates the user interface of an application into individual pieces, known as Components. Those components need to send data to each other and they do so, using props.
How can we use Props?
To use Props effectively, consider these steps:
- Create a parent component that renders some JSX.
class Parent extends React.Component{
render(){
return(
<h1>Parent</h1>
)
}
}
- Create a child component.
const Child = () => {
return <h3>I'm a child!</h3>
}
- Import the child component in the parent component.
import Child from './Child'
class Parent extends React.Component{
render(){
return(
<h1>Parent</h1>
)
}
}
- Pass in Props into the child component as a parameter.
const Child = (props) => {
return <h3>I'm a child!</h3>
}
- Render the child component in the parent component.
class Parent extends React.Component{
render(){
return(
<>
<h1>Parent</h1>
<Child text={"Child!"}/>
</>
)
}
}
- Render the Props in the child component using string interpolation.
const Child = (props) => {
return <h3>{props.text}</h3>
}
The Rules
- Props can only be sent from parent component to child component (This is called "unidirectional flow").
- Props are immutable, meaning they cannot be changed.
- Props is an object.
- Props represents data.
- Props are being passed down to components as a parameter.
Conclusion
We use props to pass data between components. The ability to pass data in this manner makes application development more efficient and makes your code more DRY. Props is a special feature to ReactJS and continues to prove the ever-evolving nature of tech. Let's continue to evolve with it!
Comment below + let's start a conversation.
Thanks for reading!
Posted on July 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.