Hello world with React

Hello world with React
0

#1

Hi,
I’m doing my first file:
I have this error.

MyComponent.render(): A valid React element (or null) must be returned. 
You may have returned undefined, an array or some other invalid object.(…)


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="https://unpkg.com/[email protected]/dist/react.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
  </head>
  <body>
    <div class='react-container'></div>

    <script type='text/babel'>
      var MyComponent = React.createClass({
        render() {
          return 
            <div>
              <h1>Hello People</h1>
              <p>My first React component</p>
            </div>
        }
      })
      ReactDOM.render(
        <MyComponent />,
        document.querySelector('.react-container')
      )
    </script>
  </body>
</html>

#2

I am on my phone, so I can’t test it. But shouldn’t the HTML you return in the render function be wrapped in parentheses? Wild guess, though.


#3

I always returned something wrapped in parenthesis like this:

render() {
return (
    <div>
      <h1>Hello People</h1>
      <p>My first React component</p>
    </div>
  );
}

I am not sure that will fix, but just an idea.


#4

Your correct, it has to be inside ( … ) so that it knows it is html.


#5

It works now and without the (…), I don’t really know why ?

    <div class='react-container'></div>
    <script type="text/babel">
        var MyComponent = React.createClass({
            render() {
                return <div>
                    <h1>Hello World</h1>
                    <p>This is my first React component!</p>
                </div>
            }
        })

        ReactDOM.render(<MyComponent />,
          document.querySelector('.react-container'))

    </script>

#6

Because you have the <div> on the same line as the return statement. If you put it a line lower, you have to have either the first part or a parenthesis on the return line so the compiler knows what to do.


#7

I know why, because I have a break line after the return, React don’t like it

                return
                <div>
                    <h1>Hello World</h1>
                    <p>This is my first React component!</p>
                </div>

#8

That is correct! :slight_smile:


#9

we’re posted in the same time…