Search code examples
reactjsreact-props

why should we write props in curly braces while using in child component


While passing prop as an argument in Person(Child Component) function why we should write props in curly braces?

App.js

import React from 'react';
import Person from './Person';

const App = () => {
  return (
  <div>
     <Person name={"John"} /> 
  </div>
);
}

export default App;

Person.js

import React from 'react';

const Person = ({name}) => {       //I am talking about this line
  return (
  <div>
     <h1/>My name is {name}.</h1>
  </div>
);
}

export default Person;

Solution

  • If the string prop to be passed down is static - as it is here - there's no need to.

    <Person name="John" /> 
    

    will work just fine.

    You need {}s whenever the value to be passed down isn't static - for example, when it comes from a variable:

    <Person name={nameFromState} /> 
    

    You also need {}s when interpolating anything into JSX (outside of props), as you see in

    <h1/>My name is {name}.</h1>
    

    This line

    const Person = ({name}) => {
    

    is just destructuring, which is equivalent to

    const Person = (props) => {
      const { name } = props;
    

    which is equivalent to

    const Person = (props) => {
      const name = props.name;
    

    All of those possibilities work just fine, but some prefer to destructure in the argument list to make things more concise.