Complete ReactJS Guide


To be continued …
React JS is a JavaScript library thats runs in the browser. React is all about component to building an application. We can divide a website into a number of components, like header, sidebar, widgets etc. By writing react components we can reuse those components across various pages in our website or web application.

Through react we can write custom html element.

Installation

We need Node Package Manager (npm) to create a react application. npm comes with Node.js.

Installing Node.js

Go to the Node.js website by clicking this Download Node.js and download the appropriate Node.Js installers based on your operating system. And simply install it by clicking. Its pretty straight forward.

Creating your first React App

If you are using mac then go to your terminal and run this code

// installing create-react-app globally
npm install -g create-react-app
//creating react application using create-react-app
create-react-app my-react-app
// going to the folder where I created my-react-app folder/project
cd my-react-app
//will start the react project
npm start

After typing npm start you will be redirected to the browser and can see your newly created react application. In most cases your react application URL will be http://localhost:3000

React Components

There are mainly two types of component in React JS one is class based component and the other is functional component.

Class Based Component

The classs based component will be a class which will render some JSX code. Though JSX code looks like html but actually its javaScript. The classname will be followed by the file name of the component. In that case it is Todos.

At the end of the component we have to export it for future use inside other components.

//importing React and Component from React provided libraries
import React, {Component} from 'react';
// class name will be similar to your file name
// here my file is Todos.js and my Classname is Todos
class Todos extends Component{
	//render method returns some JSX code
	//JSX code looks like html but actually it is Javascript
	render(){
		return (<div><h1>This is Todos component</h1></div>);
	}
}
export default todos;
// exporting this component, by using this we will be able to 
// use this component inside other component 
// you have to export the same class name i.e Todos here export default Todos

Functional Component

A functional component will be a function that might receive some props (parameters) from another component. Unlike class based component it will not use render() function. Instead it will return some JSX code.

Class based component name starts with a capital letter but functional component name can be starts with a lowercase or uppercase letter.

import React from 'react';
function todo(props){
	return <h2>My Todo</h2>;
}
export default todo;

We can write the functional component in a different way using es6 JavaScript arrow function. Both the arrow function and normal function will do the same thing for you but here we will mostly follow the arrow function.

import React from 'react';
const todo = (props) => {
	return <h2>My Todo</h2>; 
} 
export default todo;

CSS module in ReactJS

You can use react’s CSS module to add css file into your component. The name of the css file will be the component-name.module.css. You must have to use .module inside your css file name otherwise it can’t be linked.

Here our css file name is Todos.module.css and we have a .Todos class inside our css file.

We imported our css file and gave it a name classes. We can access our css classess inside that component by using className = {classes.Todos}

import React, {Component} from 'react';
// here the css file name is Todos.module.css
// you must have to keep .module in the name of css file 
import classes from './Todos.module.css';

class Todos extends Component{
	render(){
		return(
			// you have to use className property to add a css class
			// .Todos is a css class defined in the Todos.module.css file
			// you have to access the class using classe.Todos
			<div>
				<h1>This is Todos component</h1>
			</div>
		);
	} 
} 
export default Todos;

Our Todos.module.css file

.Todos{}
.Todos h1{color:green;}

Passing values between components using props

We can pass values between components using props. Our App.js file imports the Todos.js file and hence its rendering the Todos component by using

import React from 'react';
import './App.css';
import Todos from './Todos/Todos';
function App() {
  return (
    <div className="App">
        <Todos />
    </div>
  );
}

export default App;

Our Todos component calling some Todo components and passing some values “title”.

import React, {Component} from 'react';
import classes from './Todos.module.css';
import Todo from './Todo/Todo';
class Todos extends Component{
	render(){
		return(
			<div>
				<h1>This is Todos component</h1>
				<Todo title="Task 1" />
				<Todo title="Task 2" />
			</div>
		); 
	} 
} 
export default Todos;

The Todo component take the title value from Todos component as props and printing the values by using {props.title}. It is not necessary to name it as props, you can give it any names like myValues etc.

const todo = (props) => {
	return <h2>{props.title}</h2>; 
} 
export default todo;

Props Children

Children is a type of parameter that can be passed to other components without calling anything.

Instead of calling our Todo component as <Todo title="Task1" /> we can also call it as <Todo title="Task1">My Task:</Todo>. Here “My Task:” text is also available as props to the Todo component and you can access this value by using {props.chidlren}.

import React, {Component} from 'react';
import classes from './Todos.module.css';
import Todo from './Todo/Todo';
class Todos extends Component{
	render(){
		return(
			<div>
				<h1>My Todo List</h1>
					<Todo title="Task1">My Task:</Todo> 
					<Todo title="Task1">My Task:</Todo> 

			</div>
		); 
	} 
} 
export default Todos;
import React from 'react';

const todo = (props) => {
	return <h2>{props.children} {props.title}</h2>; 
} 
export default todo;
My Todo List
My Task: task 1
My Task: task 2

Using State

We can use state to to store data inside a component. Props gives value from outside the component where as state works inside the component.

Using state in Class based Component

Here in the example below we can store all of our todo list inside state. You can access the state value using this.state.tasks. You can use state like only in class based component, for functional component you have to use react hook useState (will be found in the next section).

In this example below the tasks arrays of tasks. We can print this value using Javascript map function

import React, {Component} from 'react';
import classes from './Todos.module.css';
import Todo from './Todo/Todo';

class Todos extends Component{
	state = {
		tasks:[
			{id:1, title: "Learn CSS"},
			{id:2, title: "Learn HTML"},
			{id:3, title: "Learn JavaScript"}
		],
		showTodos: true
	};

	toggleTodosHandler = () =>{
		this.setState({showTodos: !this.state.showTodos});
	}

	render(){

		let todoList = '';
		let toggleButtonText = 'Show Todos';

		if(this.state.showTodos){
			toggleButtonText = 'Hide Todos';
			todoList = <div>
							{
								this.state.tasks.map((todo,index) => {
								return <Todo key={todo.id} title={todo.title}>My Task: </Todo>;
								})
							}
						</div>;
		}

		return(
			<div className={classes.Todos}>
				<h1>My Todo List</h1>
				<button onClick={this.toggleTodosHandler}>{toggleButtonText}</button>	
				{todoList}
				
			</div>
		);
	}
}
export default Todos;

Using useState to manage State on Functional Component

In the functional component you can not use state directly. Instead you have to call a react hook useState.

useState() always returns arrays of two functional elements. First elements can be used to accessing the value and the second element will be used to change the value for the state.

There is a special case for useState. Unlike class based state if you want to use a single value inside the state you have to redeclare other values too, otherwise those values will be lost. To keep things tidy its better to declare each values individually by using separate useState() function.

import React, {useState} from 'react';
import classes from './Todos.module.css';
import Todo from './Todo/Todo';

const Todos = (props) => {
	const [todosState, setTodosState] = useState({
		tasks:[
			{id:1, title: "Learn CSS"},
			{id:2, title: "Learn HTML"},
			{id:3, title: "Learn JavaScript"}
		],
		//showTodos: true
	});

	const [showTodosState,setShowTodosState] = useState(true);

	const toggleTodosHandler = () =>{
		setShowTodosState(!showTodosState);
	}

	let todoList = '';
	let toggleButtonText = 'Show Todos';

	if(showTodosState){
		toggleButtonText = 'Hide Todos';
		todoList = 
			<div>
				{
					todosState.tasks.map((todo,index) => {
						return <Todo key={todo.id} title={todo.title}>My Task: </Todo>;
					})
				}
			</div>;
	}

	return(
		<div className={classes.Todos}>
			<h1>My Todo List</h1>
			<button onClick={toggleTodosHandler}>{toggleButtonText}</button>	
			{todoList}
			
		</div>
	);
};

export default Todos;

Using Constructor

We can modify our previous example like the code below by using constructor.

When you declare constructor you have to pass props to constructor and have to declare super(props). These two things are mandatory.

Now inside the constructor we can declare our state by using this.state.

import React, {Component} from 'react';
import classes from './Todos.module.css';
import Todo from './Todo/Todo';

class Todos extends Component{
	
	constructor(props) {
		super(props); // You have to declare this all the time
		this.state = {
			tasks:[
				{id:1, title: "Learn CSS"},
				{id:2, title: "Learn HTML"},
				{id:3, title: "Learn JavaScript"}
			],
			showTasks: false
		};
		
	}

	render(){

		let todoList = '';
		// using javascript map function to print the tasks array
		todoList = this.state.tasks.map((todo,index) => {
			return My Task: ;
		});

		return(
			<div>
				<h1>My Todo List</h1>
				{todoList}
			</div>
		);
	} 
} 
export default Todos;

But declaring constructor redundant. React itself manages all these things internally and you do not need to declare constructor again unless you have to perform some special operation inside constructor. We will follow our pervious example, which is without declaring constructor.

,