An Intro to React- A Javascript Library

Ebube .E
9 min readFeb 12, 2023

--

Photo by Gabriel Heinzer on Unsplash

Have you ever been to a website where you can interact with the page in real-time? Maybe you’ve noticed that the page updates without having to refresh the entire thing? That’s all thanks to React!

React is a JavaScript library that was first released by Facebook in 2013. It was initially used for Facebook’s own website, but it quickly gained popularity among developers because of its ability to build user interfaces with dynamic and responsive elements.

Before React, developers had to use a combination of HTML, CSS, and JavaScript to make dynamic pages, which could lead to messy and difficult-to-maintain code. React changed all that by allowing developers to create reusable UI components that can be easily manipulated and updated.

So, what exactly is React used for?

React is commonly used for building single-page applications, where a user interacts with the page without needing to reload it. It’s also used for creating mobile apps, as well as for improving the performance of slow loading web pages.

React uses a virtual DOM (Document Object Model), which is a lightweight in-memory representation of the actual DOM. This means that instead of directly manipulating the actual DOM, React updates the virtual DOM first, and then the virtual DOM updates the real DOM, leading to faster updates and rendering.

Getting Started

WARNING: DO NOT LEARN REACT BEFORE JAVASCRIPT UNLESS YOU LOVE SUFFERING😭!

To get started, you’ll need to have a basic understanding of React and its components. You’ll also need a code editor and a terminal to set up your project.

A few basics of React will be explained to the best of my knowledge here(P.S I’m still a beginner😅)

React Component

A component in React is a reusable piece of UI (User Interface) that encapsulates a specific behavior or visual representation. Think of components as building blocks for your application’s UI.

You can use these components to build a complex UI by composing them together.

For example, you can have a component for displaying a navigation bar at the top of your website and another component for showing a list of items.

You can then use these components in your main app component to build a complete UI.

Here’s an example of a simple React component:

import React from 'react';
const Header = () => {
return (
<div className="header" >
<h1>To -Do List</h1>
</div>
)
}
export default Header

In this example, we’ve defined a component called Header.js that returns some JSX(JavaScript syntax extension) to render a header. You can use this component in another component by importing it and including it in the JSX, like so:

import React from 'react'; import Header from "./components/Header";
const App = () => {
return (
<div> <MyComponent /> </div> );
};
export default App;

In this example, the App component includes the MyComponent component, and when the App component is rendered, the value in the MyComponent component is returned

Since you’ve got this, let’s move over to props

React Component Props Explained

Props in React are short for “properties,” and they are a way of passing data from a parent component to its child component(s).

Props allow you to reuse components and make them more flexible and generic, so you don’t have to rewrite the same component every time you need to use it with different data.

In React, you can define the props that a component should receive as arguments in the component’s function or class definition.

Then, when you render the component, you can pass the props to it by including them as attributes on the component’s HTML-like JSX tag.

For example, consider a component called Greeting that displays a greeting message to the user:

function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }

Here, the component Greeting receives a props object as an argument, which contains the name prop passed to it by the parent component. The component uses this prop to display the user’s name in the greeting message.

You can then use this component in another component like this:

function App() { return <Greeting name="John" />; }

This will render a page with the text “Hello, John!” on it.

In summary, props in React allow you to pass data from a parent component to its child component(s), making your components more flexible and reusable.

UseState in React

useState is a hook in React that allows you to add state to your functional components.

‘State’ is a way to store and manage data that affects the render of a component. It allows you to keep track of certain values in your component that can change over time and re-render the component when the state values change.

useState returns an array with two elements: the current state value, and a function that you can use to update that state value.

When you call the update function, it will cause the component to re-render and reflect the updated state.

Here’s a simple example of how you could use useState in a functional component:

import React, { useState } from 'react'; 
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div> ); }

In this example, we are using useState to store a count of how many times a button has been clicked. The initial state value is 0. When the button is clicked, we call setCount to update the state and increment the count by 1.

Up next, react hooks!

React Hooks Explained

An easy way to describe hooks in React with examples

React Hooks are a new feature in React 16.8 that allow you to add state and other React features to functional components.

They make it possible to write components that are much simpler, cleaner, and more reusable, without having to use class components.

Here are some examples of commonly used hooks:

useState: This hook allows you to add state to your functional components. It returns an array with two elements, the first being the current state, and the second being a function that updates it.

import React, { useState } from 'react'; 
function Example() { // Declare a state variable called "count"
const [count, setCount] = useState(0);
return (
<div> <p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div> );
}

useEffect: This hook lets you perform side effects in functional components. An example use case would be to fetch data from an API, or to update the document title when the component is mounted and unmounted.

import React, { useState, useEffect } from 'react';
function Example() { const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate
useEffect(() => { document.title = `You clicked ${count} times`; });
return ( <div>)

Now that we’ve got this down, let’s try to build a simple project in React.

First, I’m just gonna assume you have your code editor and terminal ready.

Go to your terminal and install React. If you don’t know how to check out this link

Next, open your code editor and make a new folder.

Then, navigate to that folder in your terminal

To do this type cd ‘folder name’

Then, them npm run start

And ta-da, you’ve started your first react project. Good job!

Photo by Isabel Maria Guner-Velasco on Unsplash

Let’s get on with the building then. In today’s episode, we will be creating a CRUD react to-do list app

In this article, we’ll learn how to create a to-do list app using React, a popular JavaScript library for building user interfaces. We’ll also implement CRUD (Create, Read, Update, Delete) functionality, allowing us to perform the basic operations on our list of tasks.

First, create a new React project by running the following command in your terminal:

npx create-react-app my-todo-app

This will set up a new React project with a default file structure. Navigate to the project directory and start the development server by running:

cd my-todo-app npm start

Creating the To-Do List Component

Next, let’s create the To-Do List component. This component will display our list of tasks and provide the ability to add, update, and delete tasks.

First, click on the public inbuilt folder(really don’t know why this called public).

Anyways, you’ll see an index. html file. This file, my friend is the skeleton of your web app. Under the body tag, you’ll see a div with an id of root. Incase, you’re wondering what to do with that, you’ll it in a sec.

Navigate to the file called index.js, then add your root id to render the html document like so:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);

Secondly, navigate your way to the app.css file and make your styles. The classes used in the CSS file will be used in your Javascript.

Then,create a new file in the src directory named Components. In this folder, create a file called form.js. Input the following code:

import React, {useEffect} from "react";
import { v4 as uuidv4 } from "uuid";
const form = ({ input, setInput, tasks, setTasks, editTask, setEditTask}) => {
const updateTask=(title,id,completed)=>{
const newTask =tasks.map((task)=>
task.id===id ? {title,id,completed}: task
);
setTasks(newTask);
setEditTask("");
};
useEffect(()=>{
if(editTask){
setInput(editTask.title);
} else{
setInput("")
}
}, [setInput, editTask]);
const onInputChange = (event) => {
setInput(event.target.value);
};
const onFormSubmit = (event) => {
event.preventDefault();
if(!editTask){
setTasks([…tasks, { id: uuidv4(), title: input, completed: false }]);
setInput("");
} else{
updateTask(input, editTask.id, editTask.completed)
}
};
return (
<form onSubmit={onFormSubmit}>
<input
type="text"
placeholder="Enter a Task…"
className="task-input"
value={input}
required
onChange={onInputChange}
/>
<button
className="button-add"
type="submit">
{editTask ? "OK": "Add"}
</button>
</form>
);
};
export default form;

This creates the input field where a user can insert their tasks and add them to the list-item.

Also,in the component folder, create another file called header.js and write the following code:

import React from 'react';
const Header = () => {
return (
<div className="header" >
<h1>To -Do List</h1>
</div>
)
}
export default Header

This creates a header on the app being made.

Finally, create another file under the components folder called ‘to-do-list.js and include the following code:

import React from "react";
const TodoList = ({ tasks, setTasks, setEditTask}) => {
const handleComplete = (task) => {
setTasks(tasks.map((item)=>{
if (item.id === task.id) {
return {…item,completed:!item.completed}
}
return item
})
)
};
const handleEdit=({id})=>{
const findTask = tasks.find((task) =>task.id===id);
setEditTask(findTask)
}
const handleDelete = ({ id }) => {
setTasks(tasks.filter((task)=>task.id !==id));
};

With this, youre on your way to making the buttons on your app fully functional. To see the entire code, check out this link:

Now that we’re done with the dirty work, navigate to your app.js file and include these lines of code

import React, { useState, useEffect } from "react";
import Header from "./components/Header";
import Form from "./components/Form";
import "./App.css";
import TodoList from "./components/to-do list";

P.S Your react app will break if you do not do this. This inbuilt file specifically controls what is seen by the user.

With this, youre done with building your first to-do list in React. If you want to see what your project is meant to look like, head on out to this link:

React has come a long way since its inception in 2013.

It has revolutionised the way we build user interfaces and has made it easier for developers to create dynamic and responsive pages.

With its virtual DOM and easy integration with other technologies, React continues to be a popular choice among developers.

With that, we’ve come to the end of the show.

If you enjoyed this, give this 50 claps as a way of appreciation. Also leave a comment, share this post with your homies and follow me

--

--

Ebube .E

Bringing you insights about programming, minimal living, psychology and mental health and everything in between