0

My plan is to have a html call a react component (to test the react component, so the 1st thing i'm trying is a react class.

This is my the react file

class Hello extends React.Component {
    render() {
        return React.createElement("h1", {}, "Hello ");
    }
}

const HelloElement = React.createElement(Hello, {name: "World"});
ReactDOM.render(HelloElement, document.getElementById('mydiv'));

This is the html file,

<!DOCTYPE html>
<html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>

<body>

<script src="Hello.js"></script>
<div id="mydiv"></div>

</body>
</html>

But i get Error Decoder which is Target container is not a DOM element.

How to fix this pls ?

1
  • 1
    Your import order is wrong. Put your <script/> tag after the div declaration. Commented Feb 14, 2020 at 23:16

1 Answer 1

1

Samuel already wrote it in his comment... you need to put the <script src="Hello.js"> behind the div

The code executes in order, so when Hello.js runs, the div with id='mydiv' doesn't exist yet. Otherwise your code works just fine. All you need is to make use of that name prop.

class Hello extends React.Component {
  render() {
        return React.createElement("h1", {}, "Hello " + this.props.name);
  }
}
const HelloElement = React.createElement(Hello, {name: "World"});
ReactDOM.render(HelloElement, document.getElementById('mydiv'));
<!DOCTYPE html>
<html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<body>
<div id="mydiv"></div>
</body>
</html>

As you use React.createElement instead of JSX you also don't need Babel so far.

Sign up to request clarification or add additional context in comments.

1 Comment

A follow up question, in the render(), if i change to return (<h2>h4</h2>); it says "Unexpected token <", how to fix it pls ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.