Props (short for properties) are used in React to pass data from one component to another, typically from a parent to a child component.
HTML elements come with default attributes such as href
for links and src
for sources of media elements. These attributes should not be repurposed as props.
To inspect default attributes on a website:
$0
followed by pressing Enter. This selects the element.$0.<attributeName>
and press Enter to view the value of the attribute.More on: Console Utilities
You can create custom attributes and pass their values to components as props.
<Blog title="Learn HTML" content="Lorem ipsum dolor sit amet." />
<Blog title="Style your HTML" content="Lorem ipsum dolor sit amet." />
<Blog title="Beginner in Javascript" content="Lorem ipsum dolor sit amet." />
In the component, props are accessed via the props
parameter:
const Blog = (props) => {
return (
<div className="blogDiv">
<h2 className="title">{props.title}</h2>
<p className="content" id="content">{props.content}</p>
</div>
);
};
export default Blog;
For easier access, you can destructure props:
const Blog = ({ title, content }) => {
return (
<div className="blogDiv">
<h2 className="title">{title}</h2>
<p className="content" id="content">{content}</p>
</div>
);
};
export default Blog;
While props are typically passed from parent to child, you can also pass data from child to parent using callback functions.
Parent Component:
import React, { useState } from 'react';
import Blog from './Blog';
const ParentComponent = () => {
const [type, setType] = useState('');
const dataType = (data) => {
setType(data);
};
return (
<>
<Blog type={dataType} />
<p>The type is: {type}</p>
</>
);
};
export default ParentComponent;
Child Component:
const Blog = (props) => {
props.type('tech');
const { title, content } = props;
return (
<div className="blogDiv">
<h2 className="title">{title}</h2>
<p className="content" id="content">{content}</p>
</div>
);
};
export default Blog;
Here, the Blog
component calls props.type('tech')
to pass data back to the parent component.
Objective: Create a parent and child component where the child sends data back to the parent using props.
Create the Parent Component:
import React, { useState } from 'react';
import Blog from './Blog';
const ParentComponent = () => {
const [type, setType] = useState('');
const dataType = (data) => {
setType(data);
};
return (
<>
<Blog type={dataType} />
<p>The type is: {type}</p>
</>
);
};
export default ParentComponent;
Create the Child Component:
const Blog = (props) => {
props.type('tech');
const { title, content } = props;
return (
<div className="blogDiv">
<h2 className="title">{title}</h2>
<p className="content" id="content">{content}</p>
</div>
);
};
export default Blog;
Run Your Application:
This task will help you understand how to pass props from child to parent components in React.