Search code examples
javascripthtmlreactjsfrontendweb-deployment

React: Nothing was returned from render. This usually means a return statement is missing


How can I fix this error being thrown?

Error: CountryList(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './Containers/App';
import reportWebVitals from './reportWebVitals';
import 'tachyons';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

App.js

import React, { Component } from 'react';
import './App.css';
import NavBar from '../Components/NavBar';
import SideBar from '../Components/SideBar';
import CountryList from '../Components/CountryList';

class App extends Component {

  constructor() {
    super();
    this.state = {
      nations: []
    }
  }

  componentDidMount() {
    fetch('https://restcountries.eu/rest/v2/all%27)
      .then(response => response.json())
      .then(x => this.setState({ nations: x }));
  }

  render() {
    const { nations } = this.state;
    return (
      <div>
        <NavBar />
        <SideBar>
          <CountryList nations={nations} />
        </SideBar>
      </div>
    );
  }

}

export default App;

Solution

  • You probably does not return anything from CountryList component. You should check your return statement. If you put any conditions for nations prop, maybe you did something wrong. I guess you did like this.

    CountryList extends React.Component{
      if(nations) {
         return nations.map(nation => ...)
      }
    }
    

    but you should do like this

     CountryList extends React.Component{
          if(nations) {
             return nations.map(nation => ...)
          } else {
             return null;
          }
        }
    

    or better approach:

     CountryList extends React.Component{
         // ...do some stuff before return
         return (
             this.props.nations?.length > 0 && this.props.nations.map(....)
         )
    
         
     }