JSX attributes must only be assigned a non-empty expression

avatar

Borislav Hadzhiev

Mon Apr 04 20222 min read

banner

Photo by Raychan

JSX attributes must only be assigned a non-empty expression #

The React.js error "JSX attributes must only be assigned a non-empty expression" occurs when we forget to pass a prop value for a component. To solve the error pass a prop value to the component or remove the prop declaration.

jsx attributes must only bet assigned non empty

Here is an example of how the error occurs.

App.js
import React from 'react'; import {Header} from './Header'; export default function App() { return ( <div> {/* ⛔️ JSX attributes must only be assigned a non-empty 'expression'. */} <Header message={} /> </div> ); }

The error was caused because we declared a message prop on the Header component, but didn't set a value for it.

Most of the time your error message will underline to the prop that caused the issue.

One way to solve the error is to pass a prop to the component.

App.js
import React from 'react'; import {Header} from './Header'; export default function App() { return ( <div> <Header message={4200} objProp={{name: 'James', age: 30}} /> </div> ); }

Notice that when passing an object prop we use two sets of curly braces.

Now the Header component can use the passed in props.

Header.js
export function Header({message, objProp}) { return ( <div> <h2>Message: {message}</h2> <h2>{objProp.name}</h2> <h2>{objProp.age}</h2> </div> ); }
If the error is not resolved, you have to restart your development server and reload your IDE.

You would pass a function as a prop in the same way:

App.js
import React from 'react'; import {Header} from './Header'; export default function App() { return ( <div> <Header message={4200} changeHandler={event => { console.log(event.target.value); }} /> </div> ); }

And this is how we would use the changeHandler function in our Header component.

Header.js
export function Header({message, changeHandler}) { return ( <div> <h2>Message: {message}</h2> <input type="text" onChange={changeHandler} /> </div> ); }

An alternative solution to the error is to remove the empty prop declaration.

App.js
import React from 'react'; import {Header} from './Header'; export default function App() { return ( <div> <Header /> </div> ); }

We have no empty prop declarations in the example above, so the error is resolved.

Use the search field on my Home Page to filter through my more than 1,000 articles.