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/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/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>
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.
1 Like
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.
Your correct, it has to be inside ( … ) so that it knows it is html.
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>
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.
1 Like
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>
we’re posted in the same time…
1 Like