Thursday, August 2, 2018

Basic Component example in React

This example is similar to the previous HelloWorld example, except that we will use a seperate file for the HelloWorld react component.
The example contains 3 files index.html, index.jsx and HelloWorld,jsx

The index.html is the template file into which the react component will be loaded.
The index.jsx file contains the ReactDOM.render() which loads the React component in the HTML template.
The HelloWorld.jsx file is the React component file which contains a HelloWorld component.

Apart from these files we will need to setup the environment to take care of compiling the .jsx files and rendering the component to the browser. For this example am using a "webpack-react-boilerplate" which takes care of setting up the environment so that we can focus on the actual example.

<html lang="en">
    <title>Hello World</title>
<div id="app"></div>

import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './HelloWorld.jsx';

ReactDOM.render(<HelloWorld />, document.getElementById('app'));

import React, { Component } from 'react';

class HelloWorld extends Component {
  constructor(props) {
    this.state = {};

  render() {
return (
<span>Hello World</span>

export default HelloWorld;

The index,html file has a div tag with id="app", this will be the placeholder for the React component.

The HelloWorld.jsx has the react component which is exported using 
export default HelloWorld

The index.jsx file imports the HelloWorld component and loads the component in the div tag using ReactDOM.render().

import HelloWorld from './HelloWorld.jsx';
ReactDOM.render(<HelloWorld />, document.getElementById('app'));

Search Flipkart Products:

No comments: