Creating a React Component in this project

In this post, I will guide you how to create a React Component step-by-step

Step 1: Create the Component

Create a new file in app/assets/javascripts/components , for example in this guide I will create a component called ProjectBar. So create a file named ProjectBar.jsx (use CamelCase!)

// app/assets/javascripts/components/ProjectBar.jsx

import React from 'react';

export default class ProjectBar extends React.Component {
  render() {
    return (<span>Hello</span>);
  }
}
That’s it! This is the simplest form of React Component you can make. It only renders a div element containing text Hello.

Step 2: Define its props and/or states

Let’s say, we want to be able to pass a number representing number of total tasks available. For the sake of best practice, we need to specify ProjectBar’s propTypes and defaultProps.

// app/assets/javascripts/components/ProjectBar.jsx

import React from 'react';

export default class ProjectBar extends React.Component {
  render() {
    return (<span> {this.props.total_tasks} </span>);
  }
}
ProjectBar.propTypes = {
  total_tasks: React.PropTypes.number,
}

ProjectBar.defaultProps = {
  total_tasks: 0,
}

Step 3: register them to component.js

Basically, we are using browserify that will compile a file app/assets/javascripts/application.js. This file is a manifest file that will be compiled into application.js, which will include all the files required in it. And yes, our component.js is required there.

// app/assets/javascripts/component.js

...
ProjectBar = require('./components/ProjectBar.jsx');
...

Step 4: Use it

For example, let’s use it inside an index.html.haml

// app/views/project_details/index.html.haml

...
= react_component 'ProjectBar', { total_tasks: 10 }
...

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