Home > Mobile >  ReactJS how to pass child component title from parent component
ReactJS how to pass child component title from parent component

Time:03-25

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;

CodePudding user response:

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;

CodePudding user response:

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;
  • Related