Learn react on railsSort Order

React: Our First Component

In this episode we show you how to render your first react component.

We'll kick off the process with setting up react. Go ahead and install the packages.

npm install react react-dom --save

This time we will use the --save flag because react will be considered production dependency.

We can now import react into our project. In the entry.js add the following.

// ...import React from "react";import { render } from "react-dom";// ...

We will also remove the previous code and replace it with our first react component.

class HelloReact extends React.Component {  render() {    return(      <div id='helloReact'>        Hello From React!      </div>    );  }} 

We will also need to add a div that we can use as the root element for our react app. In index.html add the following.

<html>  <head>    <meta charset="utf-8">  </head>  <body>    <div id='root-app'></div>    <script type="text/javascript" src="bundle.js" charset="utf-8"></script>  </body></html>

We will now render the react component into the <div id='root-app'></div>

In entry.js add the following at the bottom after the HelloReact component.

render(<HelloReact />, document.getElementById('root-app'));

The final entry.js file will look something like this.

import "./style.css";import React from "react";import { render } from "react-dom";class HelloReact extends React.Component {  render() {    return(      <div id='helloReact'>        Hello from React!      </div>    );  }}render(<HelloReact />, document.getElementById('root-app'));

That's it! You should how see your react component being rendered in the page.

Be sure to upgrade to get access to all future react videos!