Hello there guys! in this post we are going to look at the basics of react js from scratch. React js is one of the popular frameworks out there which has grown over the years. It’s bascally written by Facebook. So let’s get started.
What is React
A JavaScript library for building user interfaces. React has three importances
Declarative:
Design simple views for each state in your application, and React efficiently updates and renders just the right components when your data changes.
Component-Based:
Build encapsulated components that manage their own state, then compose them to make complex UIs.
Learn Once, Write Anywhere:
You can develop new features in React without rewriting existing code.
Why Learn React
React is created by the Facebook project team in 2013.
In 2021 according to Stack Overflow Survey, React was listed as the number one Web Framework toppling jQuery from 2020’s survey.

Topics
1. Hello World
2. Introducing JSX
3. Rendering Elements
4. Components and Props
5. State and Lifecycle
6. Handling Events
7. Conditional Rendering
8. Lists and Keys
9. Forms
10. Composition vs Inheritance
How to install React
npx create-react-app demo-app
cd my-app
npm start
- HelloWorld Example
index.js
Inside the index.js we can have a simple example like this
Ex:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
// Hello, world!
Using the JSX a syntax extension to JavaScript that describes what the UI should look like.
Ex:
index.js
const element = <h1>Hello, world!</h1>
ReactDOM.render(element, document.getElementById('root'));
Now when you inspect Hello world in the chrome developer tools you can see the Html div root with the markup code.
2. JSX
React doesn’t require us to use JSX but it’s helpful as a visual aid when working with UI inside the JavaScript code.
JSX gives us the full power of JavaScript directly within our user interface. A good example is an above code.
We can insert javascript expressions using JSX
Ex:
const BIRTHDAY = '18.04.1982';
const element = <h1>I was born in , {BIRTHDAY}</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
JSX allows us to nest elements within one another as we would in HTML
Ex:
const greeting = (
// div is the parent element
<div>
{/* h1 and p are child elements */}
<h1>Hello!</h1>
<p>Welcome to React</p>
</div>
);
and many more examples we will be looking at as we continue…
3. Components and Props
Components let you split the UI into independent, reusable pieces.
Ex:
index.js
function Biodata(props) {
return (
<div>
<h1>{props.personName}</h1>
<h1>{props.personAge}</h1>
<h1>{props.Gender}</h1>
<h1>{props.dateofbirth}</h1>
</div>
);
}
export default function App() {
return (
<div>
<Biodata personName="Brian" personAge = "28" Gender = "male" dateofbirth = '18.07.1994'/>
<Biodata personName="John" personAge = "25" Gender = "male" dateofbirth = '18.07.1994'/>
<Biodata personName="Andrew" personAge = "28" Gender = "male" dateofbirth = '18.07.1994'/>
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
4. Lists and Keys
Using the .map() function we can convert an array into lists of elements.
Keys are used to tracking each element that is being iterated over with the .map() function.
Ex:
function Fruit(props) {
const fruits = props.fruits;
const listItems = fruits.map((fruit) =>
<li>{fruit}</li>
);
return (
<ul>{listItems}</ul>
);
}
const fruits = ['mango', 'orange', 'bananas'];
ReactDOM.render(
<Fruit fruits={fruits} />,
document.getElementById('root')
);
We can update the code as follows using keys
function Fruit(props) {
const fruits = props.fruits;
const listItems = fruits.map((fruit) =>
<li key = {fruit.toString()}>
{fruit}
</li>
);
return (
<ul>{listItems}</ul>
);
}
const fruits = ['mango', 'orange', 'bananas'];
or..
<li key = {fruit.id}> on the keys part...
{fruit}
</li>
5. State and Lifecycle
We will make a Welcome component that greets and sets up its own timer and updates itself every second.
By this, I will illustrate how State and Lifecycle work in React Js. Let’s begin
Ex:
class Welcome extends React.Component { // An ES6 class, that extends React.Component
constructor(props) { // a class constructor that assigns the initial this.state
super(props);
this.state = {date: new Date()}; // Adding Local State to a Class
}
componentDidMount() { // set up a timer whenever the Welcome is rendered to the DOM for the first time
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
componentWillUnmount() { // clear that timer whenever the DOM produced by the Welcome is removed
clearInterval(this.timerID);
}
tick () { // a method that Welcome component will run every second.
this.setState({ // uses this.setState() to schedule updates to the component local state
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello {this.props.name}.</h1>
<p>The time is {this.state.date.toLocaleTimeString()}.</p>
</div>
);
}
}
ReactDOM.render(
<Welcome name="Brian" />,
document.getElementById('root')
);
We can declare special methods on the component class to run some code when a component mounts and unmounts:
These methods are called “lifecycle methods”.
We have to add super(props) every single time we define a constructor() function inside a class-based component.
The entire reason for defining this constructor() function is to initialize our state object.
super(props) is a reference to the parent’s constructor() function, that’s all it is.
6. Handling Events
In React you need to have these two concepts in mind:
- React events are named using camelCase, rather than lowercase.
- With JSX you can pass a function as the event handler, rather than a string.
Ex:1
function Form() {
function handleSubmit(e) { // Using camelCase
e.preventDefault();
console.log('You clicked submit.'); // open the console
}
return (
<form onSubmit={handleSubmit}> // With JSX
<button type="submit">Submit</button>
</form>
);
}
//inspect the console
Ex:2
class Event extends React.Component{
clickMe() {
alert("You clicked me");
}
dontClickMe() {
alert("dont click me");
}
render() {
return (
<div>
<h1>Click buttons to see effect:</h1>
<button onClick={this.clickMe} >Click Me</button>
<button onClick={this.dontClickMe}>Don't Click Me</button>
</div>
);
}
}
ReactDOM.render(<Event />,
document.getElementById("root"));
7. Conditional Rendering
In React, you can create distinct components that encapsulate a behavior you need. Then, you can render only some of them, depending on the state of your application.
Ex:
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
// Try changing to isLoggedIn = {true or false}:
<Greeting isLoggedIn = {true} />,
document.getElementById('root')
);
8. Forms
Controlled Components
In a controlled component, form data is handled by a React component.
This means that a React component that renders a form also controls what happens in that form on subsequent user input.
Ex:
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = { // intializing the state object
name: '',
email:''
};
this.handleChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
console.log('Change detected. State updated' + name + ' = ' + value);
}
handleSubmit(event) {
alert('A form was submitted: ' + this.state.name + ' // ' + this.state.email);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} >
<div className="form-group">
<label for="nameImput">Name</label>
<input type="text" name="name" value={this.state.name} onChange={this.handleChange} className="form-control" id="nameImput" placeholder="Name" />
</div>
<div className="form-group">
<label for="emailImput">Name</label>
<input name="email" type="email" value={this.state.email} onChange={this.handleChange} className="form-control" id="emailImput" placeholder="email@domain.com" />
</div>
<input type="submit" value="Submit" className="btn btn-primary" />
</form>
</div>
)
}
}
class MainTitle extends React.Component {
render(){
return(
<h1>React Form</h1>
)
}
}
class App extends React.Component {
render(){
return(
<div>
<MainTitle/>
<ContactForm/>
</div>
)
}
}
ReactDOM.render(<App />,
document.getElementById("root"));
- Composition Vs Inheritance
Composition and inheritance are the approaches to use multiple components together in React.js.
This helps in code reuse.
Ex:
function BaseShell(props) { // baseshell component
return ( // it's basically a base shell and then putting any content inside it
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div> // dynamic content that can be passed outside this component
);
}
function ReactJs() { //reactjs component that prints a text but uses baseshell component
return (
<BaseShell color="blue">
<h1 className="Dialog-title">
I love React Js
</h1>
<p className="Dialog-message">
React Js is a popular frontend framework
</p>
</BaseShell>
);
}
ReactDOM.render(
<ReactJs />,
document.getElementById('root')
);