Home > Software engineering >  React: passing nested props to a functional component
React: passing nested props to a functional component

Time:03-04

Maybe it's a dumb question but I can't figure out how to pass a nested prop when I call the component Welcome inside the Wrapper. Does it considered a good practice to use nested properties?. If there are several answers I would like to know all of them.

function Welcome(props) {
  return (
  <>
    <h2>Hello, {props.name}</h2>
    <h2> lastname: {props.name.lastName}</h2>
  </>
  )
}

function Wrapper(props) {
  return(
    <>
      <Welcome name={ 'jota'}    />
    </>
  )
}

CodePudding user response:

You can pass a name object as a prop.

  function Welcome(props) {
  return (
  <>
    <h2>Hello, {props.name.firstName}</h2>
    <h2> lastname: {props.name.lastName}</h2>
  </>
  )
}

function Wrapper(props) {
  return(
    <>
      <Welcome name={{firstName: "Jota", lastName:"Trump"}}    />
    </>
  )
}

CodePudding user response:

You would need to pass down each prop individually for each function that you needed to call

  <CreateProfile
   onFirstNameChange={this.firstNameChange} 
   onHide={close}
   show={this.state.showModal}
  />

and then in the CreateProfile component you can either do

 const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}

with destructuring it will assign the matching property names/values to the passed in variables. The names just have to match with the properties

or just do

 const CreateProfile = (props) => {...}

and in each place call props.onHide or whatever prop you are trying to access.

CodePudding user response:

This is a simple example.

function Welcome({ person }) {
    const { firstName, lastName } = person;
    return (
        <>
            <h2>Hello, {firstName}</h2>
            <h2> lastname: {lastName}</h2>
        </>
    );
}

export default function Wrapper() {
    const person = { firstName: "Angel", lastName: "Canales" };

    return (
        <>
            <Welcome person={person} />
        </>
    );
}
  • Related