How to add the ReactJS component in HTML page?

In this section, we will learn how to add any ReactJS component in simple HTML page. Let’s suppose we need a counter button in our web page. As we know ReactJS uses for create component. We will just create component and put it on our HTML page.

Library Paths:

We need three libraries to create react component. First one use for ReactJS, second one for DOM and last one for convert the jsx into js, so that browser understand the our script.

HTML Code:

Add <div> under <body> tag and give id as “dvTest”. Our component will place in this div.

Script:

Add script tag in HTML and set type as “text/babel”. Since we will write our code in JSX format that’s why we need set type as “text/babel”. Create class “MyClass” and inherit or extends with React,Component. Our class will have three methods:

  • constructor()
    • call super() function.
    • create state “cnt” and set value “0”
    • bind counter() with “this” so that counter() method would use “this” keyword for main component.
  • counter()
    • get cnt value from state and add 1 into it and than finally update the state. (this.setState({cnt}))
  • render()
    • render() is the main method in ReactJS component. Here we return the html button with it’s state.

Finally, place this created component “MyClass” in div. By adding this line

” ReactDOM.render(, document.getElementById(‘dvTest’));”

button will show on our html page. I have added this component “Counter button” in this blog too. You may check it by clicking on this button. We can add more than one component in HTML. It’s depend on us.

<html>
<head>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js”></script>
</head>
<body>
<div id=’dvTest’></div>
<script type=”text/babel”>
class MyClass extends React.Component
{
constructor(){
super();
this.state = {cnt:0};this.counter = this.counter.bind(this)
}
counter(){
let cnt = this.state.cnt+1;this.setState({cnt})}
render(){
return(
<div>
<button onClick={this.counter}>Counter ({this.state.cnt})</button>
</div>)}}
ReactDOM.render(<MyClass />, document.getElementById(‘dvTest’));
</script>
</body>
</html>

 

Please check this out to understand the basic ReactJS.

Please check this out to understand the concept of virtual DOM in ReactJS.