Props on Props on Props
React has been a wild ride. There’s so much to explore and learn, but you won’t get very far at all if you don’t grasp onto one of the building foundations of React — props.
React is made up of many different components coming together to make one interactive web application. Without the ability to communicate information and data between these components, React might not be worthless.. but it would definitely be worth less.. If that makes sense.
With props, we can quickly pass functions, variables, data, etc., into other components. This keeps us from having to write the same code or functions over and over where ever needed. To pass props in, one must figure out where the prop lives and what components will need access to it. Find the parent component of those components (it may even be your main file where everything comes together) and start your work there.
To pass a prop, set it up as a variable where ever the component you are passing it to is rendered. For example, if Main.js renders a List.js and you need to pass information into List.js from Main.js, find where List is rendered — <List /> — and pass the prop in. A visual of the example would be:
const Main = () => {
const greeting = “Hello, world”
<List prop={greeting} />
return (
<div>
</div>
)
}
export default Main
This will pass the variable greeting into the List and you can retrieve it there and use it. You can call this prop anything. Personally, I like to label everything I am working with so there is no doubt what it is. So in this instance, I would label it as <List greeting={greeting} />. This helps to keep things cleaned and organized, but you can name it whatever makes the most sense to you.
To retrieve this prop from the component you are passing it into, simply call for it. Sticking to the example -
const List = ({ greeting }) => {
return (
<div>
<h1>{greeting}</h1>
</div>
)
}
export default List
Notice how the greeting is passed in as an argument into the List component function. This enables it to be used in the List component, so an h1 would be rendered with the words “Hello, world” on the page. You are able to pass in as many props as you need into other components.
Understanding how props are passed can really save some time and pain in the long run. Once that process is firmed up in your studies, you can move forward building onto these concepts with the confidence knowing that the foundation (props) is strong.