Nothing returned from the render in reactjs

(235 Views)


Suppose you have to import a component of React in the index.js. Sometimes you might get the following error-

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

What is return and render statement?

Render method is needed when you want to write a react component using a class method. It returns one of the following types- react elements, string and numbers, Booleans, and portals.

Return statement is applied to return the data/response/JSX elements based on where it will be used. If it will be used in the render function, you have to return the types specified in the render method.

The problem

If you are trying to import a component in React something like the one given below and getting an error, it is possible to solve with the help of multiple methods. It is a quite common error. Before knowing about the solution, it is necessary to get the knowledge of rendering.

import React from 'react'; const Search_Bar = () => { return <input />; }; export default Search_Bar;

Render is a method needed in react class components. This problem is mainly observed when you return from the render with parenthesis in the new line.

render() { return ( <div>Here comes JSX !</div> ); }

Solution

  1. The perfect way to deal with this problem is by using the following code-
  2. render() { return ( <div>Here comes JSX !</div> ); }

    When you use a stateless component in the form of arrow function, the content must be in the parenthesis “()” and not brackets “{}”. And, it is important to remove the complete function.

    const Search_Bar= () => ( <input />; );
  3. Ensure that the render is implemented correctly. In the example given below, the semicolon at the end of the return statement doesn’t matter much.
  4. render() { return ( <div>I am demo html</div> ); }
  5. Using wrong bracket in the routing can also lead to the error
  6. Wrong way

    export default () => { <BrowserRouter> <Switch> <Route exact path='/' component={ DemoComponent } /> </Switch> </BrowserRouter> }

    Correct way

    export default () => ( <BrowserRouter> <Switch> <Route exact path='/' component={ DemoComponent } /> </Switch> </BrowserRouter> )
  7. Importing the custom component from the caller class can be another reason for the error
  8. Don’t do this-

    import {MyComponent} from './components/MyComponent'

    Use

    import MyComponent from './components/MyComponent'

All these solutions work depending on the kind of mistake you did. Don’t forget to check them and then use the methods given here to solve your problem.

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Get Programming Help
Search

Play 2048 Game Online


Search Tags