Passing numbers as Props to a Component in React

avatar

Borislav Hadzhiev

Last updated: Apr 21, 2022

banner

Photo from Unsplash

Passing numbers as Props to a Component in React #

To pass a number as props to a component in React, wrap the number in curly braces, e.g. <Child num={42} />. All props you pass to a component that are not of type string have to be wrapped in curly braces.

App.js
function Child({num}) { return ( <div> <h2>the Number is: {num}</h2> </div> ); } export default function App() { return ( <div> <Child num={42} /> </div> ); }

We passed a num prop to a component. Notice that we had to wrap the prop in curly braces.

All props that are not of type 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 num prop in the child component.

The same approach has to be used when passing an object or an array as props.

App.js
function Child({num, obj, arr}) { return ( <div> <h2>the Number is: {num}</h2> <h2>name: {obj.name}</h2> <h2>first: {arr[0]}</h2> </div> ); } export default function App() { return ( <div> <Child num={42} obj={{name: 'Alice'}} arr={['a', 'b', 'c']} /> </div> ); }

Notice that we when passing an object as props, we use 2 sets of curly braces.

This first set marks the beginning of the expression, and the second set is the actual object.

Strings are the only values you can pass as props without wrapping them in curly braces.

App.js
function Child({str, num, obj, arr}) { return ( <div> <h2>the String is: {str}</h2> <h2>the Number is: {num}</h2> <h2>name: {obj.name}</h2> <h2>first: {arr[0]}</h2> </div> ); } export default function App() { return ( <div> <Child str="Hello world" num={42} obj={{name: 'Alice'}} arr={['a', 'b', 'c']} /> </div> ); }

You could also wrap the string in curly braces to be consistent, but that's not necessary.

App.js
function Child({str, num, obj, arr}) { return ( <div> <h2>the String is: {str}</h2> <h2>the Number is: {num}</h2> <h2>name: {obj.name}</h2> <h2>first: {arr[0]}</h2> </div> ); } export default function App() { return ( <div> <Child str={'Hello world'} num={42} obj={{name: 'Alice'}} arr={['a', 'b', 'c']} /> </div> ); }

If you use a template string or some logic to construct the string, you must wrap it in curly braces.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.