First React Component

In my last post, I showed how to set up the React environment — npm to download packages and their dependencies, webpack to minify and bundle code into one file for production, and Babel, a compiler that processes React into JavaScript the browser can understand.

I left off with using regular JavaScript to select an element and set its inner HTML to “Hello World!”. In this post we’ll use a React component to do that.

Writing a React component is so much easier than setting up the React environment, because React is really just JavaScript. If you are comfortable with JS, it follows that you’ll be at ease with React.

In index.js, set two variables equal to the two React modules we downloaded in my last post, react and react-dom. The syntax for loading a module is require(insert-module-name).

On line 4, we’ll define our first React component and set it to a new variable, HelloWorld. We’ll start without using ES6, in which case you can use the createClass helper to initialize a component class. Every React component includes a render function that returns the HTML you want to display in the DOM.

On line 12, we use the render method from the the ReactDOM module to update the DOM with the output from our HelloWorld component/function. We pass it the component first, the selected element last.

Next run npm run start to start the development server, visit http://localhost:8080/ and you’ll see “Hello World!” displayed.

It’s always worth using a web inspector to see what’s being rendered in the DOM.

screen-shot-2016-12-29-at-10-53-04-am

As expected, the HelloWorld component has rendered inside the app. Note how the div element we rendered was automatically assigned a data-reactroot attribute. This allows tools like react-detector to identify a React app without any hiccups.

In my next post, I’ll demonstrate how functional components and props are used to organize your UI into reusable, isolated building blocks. All react components are pure; they always return the same result given the same arguments and never change the state of variables outside of their scope (no side effects!). This makes React components easy to test.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s