Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateless component: A valid React element (or null) must be returned

I'm new to ReactJS.

I'm trying to display Hello world using the code below, but I get this error message:

What am I missing?

Code for App.js

//App.js`

import React from 'react';

const App = () => "<h1>Hello World!</h1>";

export default App;

Code for index.js

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

Code for /public/index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
like image 422
lomse Avatar asked Dec 20 '16 17:12

lomse


2 Answers

You can't wrap a JSX element in quotes.

Change this

const App = () => "<h1>Hello World!</h1>";

by this

const App = () => <h1>Hello World!</h1>;

You can also write it like this

const App = () => {    
  return <h1>Hello World!</h1>;
};

Or like this

const App = () => {
  return (
    <h1>
      Hello World!
    </h1>
  );
};
like image 91
GG. Avatar answered Oct 13 '22 06:10

GG.


You can also write it this way and avoid the return statement.

Notice the absence of curly braces, it took me some time to notice they were simple parentheses.

const App = () => (
  <h1>
    Hello World !
  </h1>
)
like image 43
IanBussieres Avatar answered Oct 13 '22 07:10

IanBussieres