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.

index.html
<html lang="en">
<head>
    <title>Hello World</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

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

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

HelloWorld.jsx
import React, { Component } from 'react';

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

  render() {
return (
<div>
<span>Hello World</span>
</div>
);
  }
}

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:
Flipkart.com

No comments: