When I started learning React, I struggled with Props. I am writing a quick overview of React Props as a small guide for those that are just learning React. Hopefully, this will prove useful for those you just starting with React.
Components
Remember that React works with components. They are small reusable pieces that are independent and are similar to JavaScript functions. Often times, these components contain information that need to be passed between other components. This is where props come in.
Props are Short for Properties
Props are pieces of information stored in components. These pieces of information are often passed to other components depending on their use. In other words, components will have props of their own depending on what has been declared. The format of props are similar to that of attributes. An attribute will be declared, along with a value for the attribute. This attribute is how a prop will be called or invoked in other components.
function BookParent() {
return (
<div>
<BookChild title="Harry Potter" author="JK Rowling"/>
<BookChild title="Game of Thrones" author="George R.R
Martin"/>
</div>
);
}
function BookChild(props) {
return (
<div>
{props.title} by {props.author}
</div>
);
}
Here we have two components. One is a parent component and one is child component of the parent. In the parent component, an attribute for title and author was declared with values. Title and Author are now properties of the parent(BookParent) component. However, BookChild does not know the values that were assigned to Title and Author. BookChild will need to pass in props and invoke title and author by using props as seen above.
Props are Passed Down from Parent to Child
As you can see the props came from the parent component. It is only being invoked by the child when it is needed. You cannot pass up a prop coming from child to parent. To do that, you would have to use a callback function(may go over this in another post). Bottom line is that props relations are parent to child!
In Summary
Props are passed down from parent to child. Yes, I know I am repeating myself but this is very important. Props are declared at the very top level component. You cannot invoke a prop that has been declared, just like how a variable will be undefined or null if it has bee declared yet.
So first you need to declare a prop in the Parent Component:
function ParentComponent() {
return (
<div>
<ChildComponent declaredAttribute={attributeValue} />
</div>
);
}
Then invoke using props in the Child Component:
function ChildComponent(props) {
return (
<div>
{props.declaredAttribute}
</div>
);
}
That prop will now render at the very top level component with the format being used in the ChildComponent.
Thank you for reading. Hope this was helpful.
Top comments (0)