2

Assume I have the following code inside my HTML file, within the <body> tags:

<div id="root"></div>

<script type="text/babel">
    class Element extends React.Component {...}

    ReactDOM.render(<Element />, document.getElementById("root");
</script>

The above code works flawlessly. However, if I change it to the following:

<div id="root"></div>

<script type="text/babel">
    class Element extends React.Component {...}

</script>

<script type="text/babel">
    ReactDOM.render(<Element />, document.getElementById("root");
</script>

I just see a blank screen.

Why does React not work if the ReactDOM.render() call is made from a separate tag?

1
  • Do you get errors in your console? Commented Oct 1, 2018 at 15:17

2 Answers 2

2

Because your scripts are of type text/babel, which means they'll get transformed into JavaScript and evaluated in different scopes. You can possibly store the class in a global variable, and retrieve it to use it in a different scope, like so:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

<script type="text/babel">
  class Element extends React.Component {
    render() {
      return (
        <h1>Hello, world!</h1>
      );
    }
  }
  
  window['Element'] = Element;
</script>

<script type="text/babel">
  var Element = window['Element']; 
  ReactDOM.render(
    <Element />, 
    document.getElementById("root")
  );
</script>

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

1 Comment

This is perfect!
2

It works fine

<html>

<head>
	<title>Parcel Sandbox</title>
	<meta charset="UTF-8" />
</head>
<body>
	<div id="root"></div>
	<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
	<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
	<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

	<script type="text/babel">
		 class Element extends React.Component {
			 render(){
				 return (
					 <div>Hello</div>
				 )
			 }
		 }
	</script>
	
	<script type="text/babel">
		ReactDOM.render( <Element/>, document.getElementById('root') );
	</script>
</body>
</html>

This is the another demo on CodeSandbox: https://codesandbox.io/s/92qv025204

1 Comment

Wow, it works when importing via the given URLs, but not from locally stored .js files. I will look into the differences. Maybe different versions?

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.