Borislav Hadzhiev
Thu Apr 21 2022·2 min read
Photo by Aron Visuals
To pass a boolean as props to a component in React, wrap the boolean in curly
braces, e.g. <Child bool={true} />
. All props you pass to a component that are
not of type string
have to be wrapped in curly braces.
function Child({bool}) { console.log(bool); return <div>{bool && <h2>Hello world</h2>}</div>; } export default function App() { return ( <div> <Child bool={true} /> </div> ); }
We passed a bool
prop to a component. Notice that we had to wrap the prop in
curly braces.
You might also see examples online that pass boolean props using just the name of the prop.
function Child({bool}) { console.log(bool); return <div>{bool && <h2>Hello world</h2>}</div>; } export default function App() { return ( <div> <Child bool /> </div> ); }
Passing the prop as bool
is the same as bool={true}
. However, if you are
passing a dynamic value (from a variable) or a false
boolean as prop, you have
to explicitly specify it like in the first code snippet.
string
have to be wrapped in curly braces when passed.The curly braces syntax lets React know that there is an expression it has to evaluate.
You can then destructure and use the bool
prop in the child component.
The same approach has to be used when passing an object or an array as props.
function Child({bool, obj, arr}) { console.log(bool); return ( <div> <div>{bool && <h2>Hello world</h2>}</div> <h2>name: {obj.name}</h2> <h2>color: {arr[0]}</h2> </div> ); } export default function App() { return ( <div> <Child bool={true} obj={{id: 1, name: 'Bob'}} arr={['blue', 'green']} /> </div> ); }
Notice that we when passing an object as props, we use 2 sets of curly braces.
Strings are the only values you can pass as props without wrapping them in curly braces.
function Child({str, bool, obj, arr}) { console.log(bool); return ( <div> <h2>{str}</h2> <div>{bool && <h2>Hello world</h2>}</div> <h2>name: {obj.name}</h2> <h2>color: {arr[0]}</h2> </div> ); } export default function App() { return ( <div> <Child str="Some content" bool={true} obj={{id: 1, name: 'Bob'}} arr={['blue', 'green']} /> </div> ); }
You could also wrap the string in curly braces to be consistent, but that's not necessary.
function Child({str, bool, obj, arr}) { console.log(bool); return ( <div> <h2>{str}</h2> <div>{bool && <h2>Hello world</h2>}</div> <h2>name: {obj.name}</h2> <h2>color: {arr[0]}</h2> </div> ); } export default function App() { return ( <div> <Child str={'Some content'} bool={true} obj={{id: 1, name: 'Bob'}} arr={['blue', 'green']} /> </div> ); }
If you use a template string or some logic to construct the string, you must wrap it in curly braces.