INTRODUCTION TO REACTJS
TABLE OF CONTENT
- What is ReactJS
- Benefits of ReactJS
- React components
- How to create a react app
- JSX
- Introduction to the use of props in ReactJs
- Brief note on hooks (useEffect and useState)
- Mapping And Key
- Case Study (Todo)
- Conclusion
WHAT IS REACTJS ?
ReactJS is an open-source, declarative javascript library used to build a website’s user interface. It was developed by Jordan, a software engineer in Facebook and it is currently managed by Facebook. React uses a virtual DOM (Document Object Model) that ensures minimal updates to the actual DOM, resulting in improved performance. DOM is the underlying tree of HTML elements that make up a document.
The virtual DOM is faster because it renders only individual elements instead of rendering all the DOM elements. ReactJS does all its necessary manipulations in the virtual DOM before making the changes in the browser DOM.
BENEFITS OF REACTJS
- It manages the state of a component
- It helps create reusable UI components reducing the number of codes used
- It renders updates to the UI efficiently in response to changes in the underlying data.
REACT COMPONENTS
They are the building block of react application. ReactJS comprises small chunks of independent, reusable codes called components which can be nested together to build a complex application. They are the heart of ReactJS. Components greatly simplify the process of creating user interfaces. You can see a user interface (UI) divided into numerous separate parts, or components, and work on them independently before merging them all into a parent component to create your final UI.
Components can be divided into two, viz:
- Functional Components: Functional components are simply Javascript functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters.
const App = ()=>
{
return <h1>Welcome Message!</h1>;
}
export default App
- Class Components: Compared to functional components, class components are a little more complex. While the class components can cooperate with one another, the functional components in your program are unaware of the other components. Data can be passed from one class component to another. To create class-based components for React, we can use JavaScript ES6 classes.
class App extends React.Component
{
render(){
return <h1>Welcome Message!</h1>;
}
}
Name of a component should always start in capital letter
- HOW TO CREATE A REACT APP
There are three ways to create react app
- Adding ReactJS directly to your html page using a script tag : Their a steps involved in adding ReactJS directly to your HTML page.
- Add a DOM container to your HTML page by creating an empty div tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
- Adding a script tag to your html page just before the body closing tag.
<!-- SCRIPT TAGS.... -->
<script src="App.js" type="text/babel"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
The App.js is the page that you will write your react code in as seen in the next step.
Then the babel helps to convert your code to ES6 and JSX
Before deploying to a live website, make sure to replace
development.js
withproduction.min.js
! Development builds of React provide more helpful error messages, but slow down your website a lot.
- Create your react component by adding a file with the name of App.js then render your app as shown below:
function App(){
return(
<h1>THIS IS MY FIRST REACT APP</h1>
)
}
ReactDOM.render(<App /> ,
document.getElementById("root")
)
In the following two methods of installing react, make sure that node
is installed properly by typing the following command on your command prompt
2. Using VITE: Vite is the latest and a more fast way to create your react app. Follow the steps below to create your first app with vite.
- Open the folder you want to install your ReactJs into and start up your terminal by either clicking
ctr+`
or by navigating to the top window bar and clicking on the terminal and then on new terminal.
- When the terminal is opened, type
npm create vite@latest
to run your ReactJs using vite. Vite installs reactjs faster than create-react-app and it consumes less data.
- Type the name of your project
- Select a react framework
- Select a javascript variant
- Cd into your project
- Type npm install
- Type npm run dev
- Copy the generated link and paste on your browser
That is it for creating your react app with vite.
3. Creating your react app using npx or yarn
- create the folder you want to install your react app in
- Then go into the directory you want your react app and type the following command for
npx
npx create-react-app my-app
cd my-app
npm start
Make sure you have your Node.js properly installed in order to use your npm package
then for yarn,
- To start a project, simply run the command below
yarn create react-app my-app
- To start the project, run the command below
yarn start
JSX
JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React. You notice on your App.jsx
a HTML like syntax inside the return
statement, it is called a JSX. It is a short hand way of writing out a tree of html element
INTRODUCTION TO THE USE OF PROPS IN REACTJS
Props are used to pass down components. Props are unidirectional, that is, they can only be passed down in one direction, majorly from the parents to the children. You can pass down props in two ways, viz:
- On the component file you want to export, type
const Entire = (props) => {
return (
<div>
<p>{props.name}</p>
<p>{props.house}</p>
</div>
)
}
export default Entire
or you can do this,
import React from 'react'
const Entire = ({name, house}) => {
return (
<div>
<p>{name}</p>
<p>{house}</p>
</div>
)
}
export default Entire
Rendering props
On the page you want to use the props, import the file and type the following commands as shown below:
import React from 'react'
import Entire from './Entire'
const Good = ( ) => {
return (
<div>
<Entire name={'Jane'} house = {'Duplex'} />
</div>
)
}
export default Good
BRIEF NOTE ON HOOKS (USESTATE AND USEEFFECT)
USESTATE HOOKS
A useState is a function that takes an initial state as a property and outputs it to a simple array of two items
. The first item is the state itself and the second item is a function used to update the state. To use a useState hook, you will first import it to your code as shown below:
import { useState } from 'react'
const [state, setState] = useState()
useState takes a variable and function, the function controls the state of the variable. Let us use a counter app to drive useState home
import React from 'react'
import { useState } from 'react'
const Good = ( ) => {
const[count, setCount] = useState(0)
return (
<div>
<h1>{count}</h1>
<button onClick={()=>setCount(count+1)}>Increase</button>
<button onClick={()=>setCount(count-1)}>Decrease</button>
</div>
)
}
export default Good
USEEFFECT
UseEffect allows us to provide functionality that responds to certain data or function in our code. It takes two parameters, the function
which is the effect and the dependencyArray
. The dependency array determines if the event gets fired or not.
import {useEffect} from 'react'
useEffect(()=>{
// return
}, [dependencyArray])
MAPPING AND KEY
A map is a type of data collection where pairs of data are stored. It has a special key inside. It is necessary to map the key to the value stored in the map. A duplicate pair cannot be kept in the map (). It is as a result of each key being uniquely stored.
The “map” method in React is used to iterate through and display a list of related objects of a component. React does not have a map feature. Instead, any array could be used by calling the default JavaScript function. The map() method calls a provided function on each element of the calling array to create a new array.
import React from 'react'
const student = [
{
id : 1,
name : 'Jane',
age: 150,
state : 'Enugu'
},
{
id : 2,
name : 'Catherine'
age: 15,
state : 'Abia'
},
{
id : 3,
name : 'Queen',
age: 20,
state : 'Akwa'
}
]
const Good = ( ) => {
return (
<div>
{
student.map(item=>(
<div key={item.id}>
<p>{item.name}</p>
<p>{item.age}</p>
<p>{item.state}</p>
</div>
))
}
</div>
)
}
export default Good
Without the key
value, an error would have been thrown on the console.
CASE STUDY (TODO LIST)
Here, we are going to drive home so far what we have learnt today by creating a simple todo list app
- Create a simple react app using any of the methods shown below and delete unnecessary files/codes that will not be needed.
- Create three components, I will name mine
Todo.jsx
, which renders a todo and handles its actions,TodoForm.jsx
which will be used for rendering the list and adding todos to our form andTodoList.jsx
which will render a list of todo.
- using
App.js
as the entry point of our App, because our todo is immutable, we need a function to update the array, hence we create a useState function that takes an array as thestate
, to get the item out of the array, we will de-structure the array.
import { useStae } from 'react'
import './App.css'
function App() {
const [todo, setTodo] = useState([])
return (
<div className="App">
</div>
)
}
export default App
- Inside the inside each of the components you created, use the
rafce
command to create a jsx boiler plate then create a simple form with an input tag and a button
- On the
TodoForm.jsx,
we will define a state that will keep track of the input from the user, the state will take an object which will have keys ofid
,task
,completed
, thetask
is the the task of the todo,completed
is used to check if the task has been completed
const [todo, setTodo] = useState({
id: "",
task: "",
completed: false
})
- create a simple form with an input and button element then define a function that will be triggered whenever a change is made on the input using the onChange even and also a function that will get triggered when our form is submitted using the onSubmit event as shown below:
return (
<div>
<form action="" onSubmit={handleSubmit} className='form'>
<input type="text"
name='task'
value={todo.task}
onChange={handleChange}
/>
<button type='submit'>Submit</button>
</form>
</div>
)
- Write a function that will be triggered whenever our input changes.
function handleChange(e){
setTodo({
...todo,
task : e.target.value
})
}
The above process is called event handling.
- In your
App.js
, create a function that will add to the todo, the function will take in a new todo, then the old todos, as shown below
function addTodo (todo){
setTodos([todo, ...todos])
}
- Pass down the
Todo
function as props in theTodoForm
component as aprop
, but first, import yourTodoForm
into your App.js
<div className="App">
<h1>TODO APP</h1>
<TodoForm addTodo={addTodo} />
</div>
- In your
TodoForm
, destructure theaddTodo
function from the props parameter
const TodoForm = ({addTodo}) => {....
- Then, you will write a function that will add to the todo whenever the form is submitted.
function handleSubmit(e){
e.preventDefault()
if(todo.task.trim()){
addTodo({...todo, id: uuid() })
setTodo({...todo, task:""})
}
}
For the id
, we will use the uuid
to create an id for each to, before you use it as shown above, first install, then import the uuid
. To install, type the following command on your terminal, make sure you are on your working directory
npm i react-uuid
Then, import uuid
to your TodoForm.jsx
component.
import React from 'react';
import uuid from 'react-uuid';
- On your
TodoList.jsx,
de-structure your todo props and then render a simple ul element, then map yourtodos
as shown below
import React from 'react'
import Todo from './Todo'
const TodoList = ({todos, toggleComplete, removeTodo}) => {
return (
<div>
<ul style={{marginTop: '30px'}}>
{
todos.map(todo =>(
<div style={{marginTop: '30px'}}>
<Todo key = {todo.id} />
</div>
))
}
</ul>
</div>
)
}
export default TodoList
Our Todo.jsx
will have three main element, the task, the checkbox and the delete button
import React from 'react'
const Todo = ({todo}) => {
return (
<div style= {{display:"flex"}} className='text'>
<li style={{textDecoration: todo.completed ? "line-through": null,
fontSize:'24px', padding:'10px 15px'
}}>
{todo.task}
</li>
<input type="checkbox"/>
</div>
)
}
export default Todo
- To add our todo to
local storage
so that it will not clear on every refresh, on yourApp.jsx
, use the following line of codes
const LOCAL_STORAGE_KEY = "react-todo-list-todos";
useEffect(()=>{
const storageTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
if(storageTodos){
setTodos(storageTodos);
}
}, [])
useEffect(()=>{
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
},
the setItem
is used to add data to your local storage and the getItem
is used for getting items from local storage
TO MAKE A TOGGLE COMPLETE AND REMOVE FUNCTION
- On your
App.js
, we will write a function that will update our todo and also delete our todo using themap
function
function toggleComplete(id) {
setTodos(
todos.map(todo => {
if (todo.id === id) {
return {
...todo,
completed: !todo.completed
};
}
return todo;
})
);
}
function removeTodo(id) {
setTodos(todos.filter(todo => todo.id !== id));
}
- Take this functions and pass it to your
TodoList.jsx
return (
<div className="App">
<h1>TODO APP</h1>
<TodoForm addTodo={addTodo} />
<TodoList todos={todos}
removeTodo={removeTodo}
toggleComplete={toggleComplete} />
</div>
)
- On your
TodoList,
destructure the props and again, pass it to yourToDo
function,
<ul style={{marginTop: '30px'}}>
{
todos.map(todo =>(
<div style={{marginTop: '30px'}}>
<Todo key = {todo.id}
todo = {todo}
removeTodo={removeTodo}
toggleComplete = {toggleComplete} />
</div>
))
- Lastly, on your
Todo.jsx
, write a function that will call thetoggleComplete
anddelete the todo
as shown below
import React from 'react'
import { AiFillDelete } from 'react-icons/ai';
import { GrCheckboxSelected, GrCheckbox } from 'react-icons/gr';
const Todo = ({todo, removeTodo, toggleComplete}) => {
function handleCheckboxClick() {
toggleComplete(todo.id);
}
function handleRemoveClick() {
removeTodo(todo.id);
}
return (
<div style= {{display:"flex"}} className='text'>
<li style={{textDecoration: todo.completed ? "line-through": null,
fontSize:'24px', padding:'10px 15px'
}}>
{todo.task}
</li>
<input type="checkbox"
checked={todo.completed}
onClick={handleCheckboxClick} />
<AiFillDelete onClick={handleRemoveClick}
style={{fontSize:'40px', color:'red', paddingTop:'10px'}}
/>
</div>
)
}
export default Todo
In the above block of code, I used react-icons
, you can install react-icon with the following command:
npm install react-icons — save
- You can now make your code look finer with some css styling
CONCLUSION
To summarize, ReactJS is a sophisticated and widely used JavaScript toolkit created primarily for designing user interfaces. Its ability to organize and render components helps developers easily design sophisticated and dynamic web apps. Because of its virtual DOM and modular design approach, it delivers exceptional speed, making it an excellent solution for large-scale applications. Furthermore, its large developer community and Facebook support make it a solid and trustworthy alternative for developing modern online apps. Overall, ReactJS is a must-have technology for anybody trying to create dynamic and interactive web user experiences.
To see the github repository, click here
Click here to view the deployed app