I recently experimented with React.js, so thought of sharing key points that I learnt. Though there are handful of material online, couldn't find one that covers all in a concise way that can help learn key aspects of ReactJS. I believe this would resonate with few and help them learn, understand and get a jumpstart with ReactJS.
What is React.js?
React.js is an open source JavaScript based library for building frontend (user interface) of a web or mobile application.
Why React.js?
Every web application core is to have a fast rendering response for better user experience. Because of this ease, users come back often and it leads to higher usage and adaptability.
Further, based on how it achieves speed, it is scalable and reusable.
How React.js Does It?
React.js works at component level. It helps break an app into many small components with their own responsibilities. This makes things simpler and scalable. With this breakdown:
- it’s easier to refresh/update a portion of view without reloading an entire page of the app
- it leads to build once and reuse across
Another key part of React.js is being declarative. There is an abstraction from details on how to do. This makes it easier to read and understand.
A declarative example would be telling my son to make a house craft from paper instead of guiding him with each step of how to get the paper, cut it, paste it to form a house craft. Of course, the assumption here has to be true that my son knows how to make it.
A quick comparison with jQuery here (it’s imperative) – it would need details on how to build the house craft.
Translating the above in JavaScript language world:
- With React – we define how we want a particular component to be rendered and we never interact with DOM to reference later
- With jQuery – we would tell the browser exactly what needs to be done using DOM elements or events need basis
Key Features
The following features help us achieve the above:
For the entire React glossary, please refer to this link.
- Components – Simple or State
These are small reusable codes that returns a React element to render. This component can have state related aspect based on need.
function ComponentExample(props) {
return <h1>Hola! {props.name}</h1>;
}
class ComponentExample extends React.Component {
render() {
return <h2>Hola! {this.props.name}</h2>;
}
}
class ComponentExample extends React.Component {
constructor(props) {
super(props);
this.state = {author: "Sandeep Mewara"};
}
render() {
return (
<div>
<h2>Hola! {this.props.name}</h2>
<p>Author: {this.state.author}</p>
</div>
);
}
}
Quote:
For above example component, use normal HTML syntax: <ComponentExample />
- Virtual DOM
DOM (Document Object Model) is a structured representation of the HTML elements present on a web page. Traditionally, one would need to get elements out of DOM to make any change. In context of an area of a webpage, it would need a lot more work to refresh it with updated content when needed.
React helps here with its declarative API. A copy of actual DOM is kept in memory which is much faster to change. Once done, React uses its ReactDOM library to sync the virtual representation of UI in memory to the actual DOM.
ReactDOM library internally keeps two VDOMs – one before update and one after. With them, React knows exactly what all to be updated in actual DOM and does all of it on the fly leading much faster updates compared to traditional DOM updates.
Quote:
React.js has a library ReactDOM to access and modify the actual DOM.
To render HTML on a webpage, use: ReactDOM.render()
- JSX (JavaScript eXtension)
JSX is a syntax extension to JavaScript that follows XML rules. It’s more of a helpful tool than requirement in React as mentioned below in their website:
Quote:
React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code
JSX converts HTML tags into React elements that are placed in DOM without any commands like createElements()
, etc.
const testHtml = <h2>Hola! Sandeep Mewara</h2>;
ReactDOM.render(testHtml, document.getElementById('root'));
const testHtml = React.createElement('h2', {}, 'Hola! Sandeep Mewara');
ReactDOM.render(testHtml, document.getElementById('root'));
Quote:
Normally, we can’t assign an HTML tag to a JavaScript variable but we can with JSX!
- Unidirectional data flow
React implements one way reactive data flow. It uses flux
as a pattern to keep data unidirectional. Interpret it as you often nest child components within higher order parent components. Snapshot of state is passed across from parent to child components via props (readonly, cannot be updated) and updates from child to parent happen via callbacks bound to some control on child component.
- ES6 compatible
React library is ES6 (ECMAScript 2015 or JavaScript 6) enabled and thus makes it easier to write code in React. Among all changes to standardize JavaScript in ES6, Classes
introduction is one of them which plays a critical role in React.
- Lifecycle
Each React component has a lifecycle that helps write a code at a specific time during the flow as per need.
class TestClass extends Component
{
constructor(props)
{
super(props);
this.state = {currentdate: new Date()};
};
componentWillMount() {
};
componentDidMount() {
};
componentWillReceiveProps() {
};
shouldComponentUpdate() {
};
componentWillUpdate() {
};
componentDidUpdate() {
};
componentWillUnmount() {
};
render()
{
return (
<h1>Current Date: {this.state.currentdate.toString()}</h1>
);
};
}
Quote:
For the entire React glossary, please refer to this link.
Sample Application Setup
We will explore and understand more from React’s demo app. We will jump start our sample app bootstrapped with Create React App.
I used yarn create react-app demo-react-app
and opened the created directory in IDE that looked like:
With the above, once I ran yarn start
in root folder demo-react-app, the app was up and running without any code change. We can see the default app hosted in browser at the following url: http://localhost:3000/.
A quick look at a few key files that connect dots that lead to the above UI view:
- public/index.html
Base file which we browse using URL. We see the HTML
defined in it. For now, the element to notice would be a div
named root
.
- src/index.js
Located at root of app, is like an entry file (like main
) for app that has code like below:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
It imported React
and related library, CSS file for app, a component named App
. After this, it defines a render
method which displays whatever is defined in component App
as page root element.
- src/App.js
Defines a function component of React that returns an HTML with React logo and a link to render.
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Q: How did index.js got connected with index.html?
Create React App uses Webpack with html-webpack-plugin underneath. This Webpack uses src/index.js as an entry point. Because of this, index.js comes into picture and all other modules referenced in it. With html-webpack-plugin configuration, it automatically adds the script tag in html page.
Let’s see with few modifications to the app now!
Specifically, I will be changing the flavour of the above three files to play around.
Few new files reference:
- AppHola.js file for a
HelloWorld
kind of change – displays my name instead of other texts - AppNavigation.js (has portion of pages updated)
- Introduction – simple display of texts
- Clock/counters auto updating
- Random color generator that updates background color of defined area
Given this was for beginners, I have not added too much of complexity to the app. I have tried to keep it as simple possible with some variance of what all can be tried.
There are plenty of imports that can be used. For example, in our demo app, to have navigation, we have used a navigation router react-router-dom
import (run npm i react-router-dom --save
inside root folder).
- For navigtion menu:
class Navigation extends Component {
render() {
return (
<HashRouter>
<div>
<h1>React.js Application</h1>
<ul className="header">
<li><NavLink exact to="/">Introduction</NavLink></li>
<li><NavLink to="/counters">Continous Counter</NavLink></li>
<li><NavLink to="/colors">Random Color</NavLink></li>
</ul>
<div className="content">
<Route exact path="/" component={Introduction}/>
<Route path="/counters" component={Counters}/>
<Route path="/colors" component={Colors}/>
</div>
</div>
</HashRouter>
);
}
}
- For Introduction menu item (returned plain simple
HTML
back with some text):
class Introduction extends Component {
render() {
return (
<div>
<h2>Hola!</h2>
<p>This is a ReactJS based sample application</p>
<p>built for learning and explaining demo use to beginners.</p>
<br />
<line></line>
<p>------- </p>
<p>
<a
className="App-link"
href="https://learnbyinsight.com"
target="_blank"
>
Sandeep Mewara
</a></p>
</div>
);
}
}
- For Counter menu item (used state component using a peek into ReactJS life cycle -
componentDidMount
& componentWillUnmount
):
class Counters extends Component {
constructor(props) {
super(props)
this.state = {
time : Date(Date.now()).toString(),
delay : 200,
start : Date(Date.now()).toString(),
counter: 0
}
}
componentDidMount() {
this.interval = setInterval(() =>
{
this.setState({
time: Date(Date.now()).toString(),
counter: this.state.counter+1
})
})
};
componentWillUnmount() {
clearInterval(this.interval);
};
render() {
return (
<div>
<h2>Timer!</h2>
<hr></hr>
<p>
Counter started at: {this.state.start}
</p>
<hr></hr>
<p>
Counter: {this.state.counter}
</p>
<hr></hr>
<p>
Current Local Time: {this.state.time}
</p>
<hr></hr>
</div>
);
}
}
- For Colors menu item (wired the
HTML
input click
event to a client script that changes background color at runtime):
class Colors extends Component {
constructor(props) {
super(props)
this.state = {
randomBackColor : '#070707'
}
}
ChangeBackColor = () => {
var rgbColorCode = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
this.setState({
randomBackColor : rgbColorCode
})
};
render() {
return (
<div>
<div style={{ backgroundColor: this.state.randomBackColor, padding:30 }}>
<p>This regions background color would change on button click</p>
<input type='button' value="Click Me!" onClick={this.ChangeBackColor} />
</div>
<div className='static'>
<p> This region will not be affected with button click</p>
</div>
</div>
);
}
}
Hope this short guide/tutorial gives a broad overview about React.JS and how to start development of the same. Keep learning!
History
- 8th July, 2020: Initial version
- 11th July, 2020: Updated