'ReactJS how to pass child component title from parent component
I am using a slick carousel component to display products for different pages, so I need to set its title from parent component: something like <Component title="Products" />
Here is the basic structure of my jsx files, can we do it with a simple method like below?
Parent.jsx:
const Parent = () => {
return (
<Component title="Products" />
);
}
export default Parent;
Component.jsx:
const Component = () => {
return (
<h3>
{title}
</h3>
);
}
export default Component;
Solution 1:[1]
You can pass data from a parent Component to a Child via the props:
const Parent = () => {
return (
<Component title="Products" />
);
}
export default Parent;
Component.jsx:
const Component = ( props ) => {
return (
<h3>
{props.title}
</h3>
);
}
export default Component;
Solution 2:[2]
You need to access the title parameter like this
Destructured parameter
const Component = ({title}) => {
return (
<h3>
{title}
</h3>
);
}
export default Component;
or like this
props parameter
const Component = (props) => {
return (
<h3>
{props.title}
</h3>
);
}
export default Component;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mgm793 |
| Solution 2 | Nice18 |
