The Questions and the Rules to Props

am20dipi

Adriana DiPietro

Posted on July 29, 2021

The Questions and the Rules to Props

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>
          )
      }
}
Enter fullscreen mode Exit fullscreen mode
  • Create a child component.
const Child = () => {  
  return <h3>I'm a child!</h3> 
}
Enter fullscreen mode Exit fullscreen mode
  • Import the child component in the parent component.
import Child from './Child'

class Parent extends React.Component{
      render(){
          return(
            <h1>Parent</h1>
          )
      }
}
Enter fullscreen mode Exit fullscreen mode
  • Pass in Props into the child component as a parameter.
const Child = (props) => {  
  return <h3>I'm a child!</h3> 
}
Enter fullscreen mode Exit fullscreen mode
  • Render the child component in the parent component.
class Parent extends React.Component{
      render(){
          return(
            <>
              <h1>Parent</h1>
              <Child text={"Child!"}/>
            </>
          )
      }
}
Enter fullscreen mode Exit fullscreen mode
  • Render the Props in the child component using string interpolation.
const Child = (props) => {  
  return <h3>{props.text}</h3> 
}
Enter fullscreen mode Exit fullscreen mode

The Rules

  1. Props can only be sent from parent component to child component (This is called "unidirectional flow").
  2. Props are immutable, meaning they cannot be changed.
  3. Props is an object.
  4. Props represents data.
  5. 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!

💖 💪 🙅 🚩
am20dipi
Adriana DiPietro

Posted on July 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related