2

I have done lots of reading online and just cant get destructuring into my head, well sort of.

//before destructuring
function me(details){
  console.log('My name is ' + details.name + ' and I work for ' + details.company);
}
//after destructuring
function me({ name, company }){
  console.log('my name is ' + name + ' and i work for ' + company);
}

me({
  name: 'Rich',
  age: 34,
  city: 'London',
  company: 'Google'
})

I've written this and this makes sense but one thing I dont get is the following in react.

if you do this:

export default ({ name }) => <h1>Hello {name}!</h1>;

<Hello name="CodeSandbox" />

why cant i do this:

export default ( name ) => <h1>Hello {name}!</h1>;

removing the {} in the function parameter?

if someone sees what im doing wrong please can they explain this?

im used to functions like so:

functionA (a) => { // do something with the parameter a }

not sure about the curlys {} inside the parameters

2
  • 2
    Because react passes the the props object to the component - { name: "asdf" }. To get the name, you need to destructure it. Commented Nov 30, 2017 at 8:10
  • Because <Hello name="CodeSandbox" /> is passed to the function something like yourFunction({name:"CodeSandbox" }) Commented Nov 30, 2017 at 8:13

1 Answer 1

6
export default (name) => <h1>Hello {name}!</h1>;

won't work because for any component, there is only one argument which is props

So in its longest form you could write

export default (props) => {
  return <h1>Hello {props.name}!</h1>;
}

which can be shortened (using destructuring) as:

export default (props) => {
  const {name} = props; // Extract name from props using destructuring
  return <h1>Hello {name}!</h1>;
}

which can be shortened (using destructuring at parameter level) as:

export default ({name}) => { // Extract name directly here
  return <h1>Hello {name}!</h1>;
}

which can be shortened (removing the function body curly braces) as:

export default ({name}) => <h1>Hello {name}!</h1>;
Sign up to request clarification or add additional context in comments.

1 Comment

this is one of the all time most helpful answers, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.