EN
React - runtime compilation in browser with Babel example
7
points
In this short article, we would like to show how to run React JSX script directly in web browser without previous compilation - it is runtime compilation.
The solution for the problem is to:
- inside
<head>
element, add the following scripts:<script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
- inside
<body>
element:- add
<div id="root"></div>
element, - add
<script type="text/babel"></script>
and paste JSX code inside,Hint: do not forget to render application inside
div#root
element (ReactDOM.render()
function).
- add
Practical examples
In this section, you can find development and production versions for the same source code.
Development version:
// ONLINE-RUNNER:browser;
<!DOCTYPE>
<html>
<head>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// Note: the below source code imports are placed automatically with UMD modules.
// import React from react';
// import ReactDOM from 'react-dom';
const Component = props => {
return (<div>My component!</div>);
};
const App = () => (
<div className="App">
<Component />
</div>
);
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
</script>
</body>
</html>
Production version:
// ONLINE-RUNNER:browser;
<!DOCTYPE>
<html>
<head>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// Note: the below source code imports are placed automatically with UMD modules.
// import React from react';
// import ReactDOM from 'react-dom';
const Component = props => {
return (<div>My component!</div>);
};
const App = () => (
<div className="App">
<Component />
</div>
);
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
</script>
</body>
</html>