Simple React example

Here is a simple React example: 

<h1>Hello, world!</h1>,

React creates a virtual DOM in memory, render outputs anything mentioned in brackets while it gets display in the HTML element whose id is ‘root’.

As we are coding in a .js file, so we can directly add javascript code in it. 

Whatever is rendered in reactJS, it can not be or updated changed. However to update it, there is need to make a new element or use inbuilt functions and pass it to ReactDOM. In example below, we are showing how to dynamically change rendered elements through javascript inbuilt function ‘setInternval’:

function tick(){

const time = (
<h1> Hello, </h1>
<h2> Time is {new Date().toLocaleTimeString()} </h2>
ReactDOM.render( time, document.getElementById('root') );

setInterval (tick, 1000);

It shows the time seconds changing in real-time. When ‘setInterval’ call the function again and again after every one second, in React it updates only time which gets changed, while rest remains same. 

One reply on “Simple React example”

Remember, while compiling these codes in React App, all the coding examples will have various imports on top of page like:

import React from ‘react’;
import ReactDOM from ‘react-dom’;
import ‘./index.css’;
import * as serviceWorker from ‘./serviceWorker’;

And at bottom of coding page:

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

Leave a Reply

Your email address will not be published.