Expected an assignment or function call and instead saw an expression in React

The error “Expected an assignment or function call and instead saw an expression” occurs in React when a return statement was missing in a function in React component. To solve this error, give a return statement to all functions in React components. You can give a return statement explicitly or implicitly on arrow functions.

We can understand how this error happens with some example codes. Please have a look at the below case.

import React from 'react'
const App = () => {
    const values = [10, 20, 30];
    const incremented = values.map((value) =>{
      // This line of code throws the error
      value+1
    })
    
    return (<div>
        App component
    </div>);
}
export default App

In the above code, the callback function of map() does not return any value, but an expression is there. This causes the error “expected an assignment or function call and instead saw an expression”.

To solve the error, give a return statement as given below.

const values = [10, 20, 30];
const incremented = values.map((value) =>{
	return value+1
})

In the above solution, we have given the return statement explicitly. For explicit return statements, we use return keyword to return values and exit from the function. If you are using an arrow function, you can give a return statement implicitly as below.

 const values = [10, 20, 30];
 const incremented = values.map((value) => value+1)

An implicit return is a short-hand method in which we didn't use curly braces at all instead, we use parentheses. Implicit return can only be applied in arrow functions. Suppose you are returning an object implicitly, then use parentheses to wrap the whole object as given below.

const getDetails = () => ({
	type:"car",
	color:"red"
})

Wrapping the whole object with parentheses is very common in the react components.

Without any return statement, some functions are useless or have no effect on the main body. You can use eslint to find such errors. ESLint checks and find problems in your javascript code. Many problems are automatically fixed by ESLint. You can customize and configure the ESLint as per your needs.

Conclusion

The React error “Expected an assignment or function call and instead saw an expression” happens when missing return statements. To solve the error give a return statement to all functions explicitly or implicitly. Implicit return is a short-hand method only possible in arrow functions.