title |
---|
Add React to a Website |
React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Whether you're working with micro-frontends, an existing system, or just giving React a try, you can start adding interactive React components to an HTML page with just a few lines of code—and no build tooling!
You can add a React component to an existing HTML page in under a minute. Try this out with your own website or an empty HTML file—all you need is an internet connection and a text editor like Notepad (or VSCode—check out our guide on how to set yours up)!
In the HTML page you want to edit, add an HTML element like an empty <div>
tag with a unique id
to mark the spot where you want to display something with React.
You can place a "container" element like this <div>
anywhere inside the <body>
tag. React will replace any existing content inside HTML elements, so they are usually empty. You can have as many of these HTML elements on one page as you need.
<!-- ... existing HTML ... -->
<div id="component-goes-here"></div>
<!-- ... existing HTML ... -->
In the HTML page, right before the closing </body>
tag, add three <script>
tags for the following files:
- react.development.js loads the core of React
- react-dom.development.js lets React render HTML elements to the DOM.
- like_button.js is where you'll write your component in step 3!
When deploying, replace "development.js" with "production.min.js".
<!-- end of the page -->
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="like_button.js"></script>
</body>
Create a file called like_button.js next to your HTML page, add this code snippet, and save the file. This code defines a React component called LikeButton
. You can learn more about making components in our guides.
'use strict';
function LikeButton() {
const [liked, setLiked] = React.useState(false);
if (liked) {
return 'You liked this!';
}
return React.createElement(
'button',
{
onClick: () => setLiked(true),
},
'Like'
);
}
Lastly, add three lines to the bottom of like_button.js. These three lines of code find the <div>
you added to your HTML in the first step, create a React app with it, and then display the "Like" button React component inside of it.
const domContainer = document.getElementById('component-goes-here');
const root = ReactDOM.createRoot(domContainer);
root.render(React.createElement(LikeButton));
Congratulations! You have just rendered your first React component to your website!
You might want to display a React component in multiple places on the same HTML page. This is most useful while React-powered parts of the page are isolated from each other. You can do this by calling ReactDOM.createRoot()
multiple times with multiple container elements.
- In index.html, add an additional container element
<div id="component-goes-here-too"></div>
. - In like_button.js, add an additional
ReactDOM.render()
for the new container element:
const root1 = ReactDOM.createRoot(
document.getElementById('component-goes-here')
);
root1.render(React.createElement(LikeButton));
const root2 = ReactDOM.createRoot(
document.getElementById('component-goes-here-too')
);
root2.render(React.createElement(LikeButton));
Check out an example that displays the "Like" button three times and passes some data to it!
Unminified JavaScript can significantly slow down page load times for your users. Before deploying your website to production, it's a good idea to minify its scripts.
- If you don't have a minification step for your scripts, here's one way to set it up.
- If you already minify your application scripts, your site will be production-ready if you ensure that the deployed HTML loads the versions of React ending in
production.min.js
like so:
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
The examples above rely on features that are natively supported by browsers. This is why like_button.js uses a JavaScript function call to tell React what to display:
return React.createElement('button', {onClick: () => setLiked(true)}, 'Like');
However, React also offers an option to use JSX, an HTML-like JavaScript syntax, instead:
return <button onClick={() => setLiked(true)}>Like</button>;
These two code snippets are equivalent. JSX is popular syntax for describing markup in JavaScript. Many people find it familiar and helpful for writing UI code--both with React and with other libraries. You might see "markup sprinkled throughout your JavaScript" in other projects!
You can play with transforming HTML markup into JSX using this online converter.
The quickest way to try JSX in your project is to add the Babel compiler to your page's <head>
along with React and ReactDOM like so:
<!-- ... rest of <head> ... -->
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<!-- ... rest of <body> ... -->
Now you can use JSX in any <script>
tag by adding type="text/babel"
attribute to it. For instance:
<script type="text/babel">
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);
</script>
To convert like_button.js to use JSX:
- In like_button.js, replace
return React.createElement(
'button',
{
onClick: () => setLiked(true),
},
'Like'
);
with:
return <button onClick={() => setLiked(true)}>Like</button>;
- In index.html, add
type="text/babel"
to the like button's script tag:
<script src="like_button.js" type="text/babel"></script>
Here is an example HTML file with JSX that you can download and play with.
This approach is fine for learning and creating simple demos. However, it makes your website slow and isn't suitable for production. When you're ready to move forward, remove this new <script>
tag and the type="text/babel"
attributes you've added. Instead, in the next section you will set up a JSX preprocessor to convert all your <script>
tags automatically.
Adding JSX to a project doesn't require complicated tools like a bundler or a development server. Adding a JSX preprocessor is a lot like adding a CSS preprocessor.
Go to your project folder in the terminal, and paste these two commands (Be sure you have Node.js installed!):
npm init -y
(if it fails, here's a fix)npm install babel-cli@6 babel-preset-react-app@3
You only need npm to install the JSX preprocessor. You won't need it for anything else. Both React and the application code can stay as <script>
tags with no changes.
Congratulations! You just added a production-ready JSX setup to your project.
You can preprocess JSX so that every time you save a file with JSX in it, the transform will be re-run, converting the JSX file into a new, plain JavaScript file.
- Create a folder called src
- In your terminal, run this command:
npx babel --watch src --out-dir . --presets react-app/prod
(Don't wait for it to finish! This command starts an automated watcher for JSX.) - Move your JSX-ified like_button.js to the new src folder (or create a like_button.js containing this JSX starter code)
The watcher will create a preprocessed like_button.js with the plain JavaScript code suitable for the browser.
If you see an error message saying "You have mistakenly installed the babel
package", you might have missed the previous step. Perform it in the same folder, and then try again.
As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called Babel, and you can learn more about it from its documentation.
If you're getting comfortable with build tools and want them to do more for you, we cover some of the most popular and approachable toolchains here.
Originally JSX was introduced to make writing components with React feel as familiar as writing HTML. Since then, the syntax has become widespread. However, there may be instances where you do not want to use or cannot use JSX. You have two options:
- Use a JSX alternative like htm which doesn't use a compiler—it uses JavaScript's native Tagged Templates.
- Use
React.createElement()
, which has a special structure explained below.
With JSX, you would write a component like so:
function Hello(props) {
return <div>Hello {props.toWhat}</div>;
}
ReactDOM.render(<Hello toWhat="World" />, document.getElementById('root'));
With React.createElement()
, you would write it like this:
function Hello(props) {
return React.createElement('div', null, `Hello ${props.toWhat}`);
}
ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('root')
);
It accepts three arguments: React.createElement(component, props, children)
. Here's how they work:
- A component, which can be a string representing an HTML element or a function component
- An object of any props you want to pass
- An object of any children the component might have, such as text strings
If you get tired of typing React.createElement()
, one common pattern is to assign a shorthand:
const e = React.createElement;
ReactDOM.render(e('div', null, 'Hello World'), document.getElementById('root'));
If you use this shorthand form for React.createElement()
, it can be almost as convenient to use React without JSX.