Write your first program in React – the easy way
To work with React in the web browser, we need to include two libraries: React and ReactDOM.
Prior to version 0.14, ReactDOM was part of React and only recently they were separated as two different libraries to facilitate React Native. ReactDOM contains
ReactDOM.render() method which is a DOM specific function used to render everything. That’s all you need to know for right now.
We also need an HTML element that will be used as a container for our first application. Both libraries are available on Facebook CDN.
<script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
- You can also download the files from Facebook’s official repository of React at Github.
- ReactDOM is needed to render React elements in the browser.
Steps to Create your First Program in React
Let’s start with creating a new file index.html using your favorite editor.
<!doctype HTML> <html lang="en"> <head> <title>My first program in React</title> </head> <body> <div id="root"> </div> </body> </html>
For example, with JSX you can write the following:
const greeting = <h1> Hello World</h1>
Putting everything together, we have the following piece of code:
<!doctype HTML> <html lang="en"> <head> <title>First program in React</title> </head> <body> <div id="root"> </div> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script type="text/babel"> ReactDOM.render( <h1>hello world</h1>, document.getElementById('root') ); </script> </body> </html>
The usage of ReactDOM
ReactDOM.render() takes two parameters:
- What you want to render. Example:
<h1> hello world</h1>
- Where you want to render. Example:
In the next lesson, we will learn about the React components. If you have any question about this lesson, feel free to leave it in the comment section below and I will reply at the earliest.
|React Installation & Configuration||Tutorial Home||React Components|