A Step-by-Step Guide to Mastering React

preciousvictory
12 min readJul 29, 2023

--

In this article, you’ll learn how to create React application, learn about how React works, and essential concepts that you need to know to build React applications. Learning React is a fantastic way to build interactive and dynamic user interfaces for web applications. If you’re a beginner venturing into web development or an experienced developer looking to expand your skill set, this article will take you through the journey of creating React applications and understanding the core concepts of React.

CONTENTS

  • Introduction
  • Prerequisites
  • npm vs npx
  • Setting Up a New Project using Create React App
  • Basic Usage
  • React Components: Function Components and Class Components
  • Styling React Components
  • React Hooks
  • Variables and props
  • Lists and conditional rendering
  • JSX
  • Resources
  • Conclusion

Introduction

React (also known as React.js or ReactJS) is a free and open-source front-end JavaScript library developed by Meta (formerly Facebook) and a community of developers. React has become one of the most popular JavaScript libraries for building user interfaces. React can be used to build interactive and responsive single-page applications and mobile, or server-rendered applications with frameworks like Next.js.

Prerequisites

Before diving into React development, there are a few essential concepts you should know before you start learning React.

  • Basic understanding of HTML & CSS.
  • Intermediate experience in JavaScript.
  • Installed Node.js and npm on your computer globally.

npm vs npx

The NPM stands for Node Package Manager and it is the default package manager for Node.js. Npm is a package installation tool.

The NPX stands for Node Package Execute and it is a tool for executing packages. It is an npm package runner that can execute any package from the npm registry without even installing that package.

if you use npm, you have to first install the create-react-app tool locally before you use create-react-app to create the app. Packages used by npm are installed globally.

npm install -g create-react-app
create-react-app my_react-app
cd my_reat-app
npm start

npx lets you run the ‘create-react-app’ code without first downloading the project. A package can be executed without installing the package.

npx create-react-app my_react_app
cd my_react_app
npm start

Setting Up a New Project using Create React App

The create-react-app tool is an officially supported way to create React applications. create-react-app will set up everything you need to run a React application. To use create-react-app, you need to have Node.js installed. If it’s not installed on your computer, install it. It’s recommended that you use the long-term support (LTS) version.

  • Run this command to create a React application named my_react_app
npx create-react-app my_react_app
  • Run this command to move to the my_react_app directory (App directory)
cd my_react_app
  • Run this command to execute the React application my_react_app
npm start

Note: Inside that app directory, you can run several commands:

  • npm start
    Starts the development server.
  • npm run build
    Bundles the app into static files for production.
  • npm test
    Starts the test runner.
  • npm run eject
    Removes this tool and copies build dependencies, configuration files
    , and scripts into the app directory. If you do this, you can’t go back!

This is the final result:

react welcome page

Application structure: create-react-app gives us everything we need to develop a React application. In a React application, the initial file structure typically includes:

├── README.md
├── node_modules
├── package.json
├── package-lock.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
├── reportWebVitals.js
└── setupTests.js

Basic Usage

Here are basic examples of using React for the web, written in JSX and JavaScript:


/** App.js file */
import "./styles.css";

export default function App() {
return (
<div className="App">
<h1>Edit src/App.js and save to reload.</h1>
<h1>Learn React</h1>
</div>
);
}
/** Index.js file */
/** React application is rendered to a root element in the HTML page */
import React from 'react';
import ReactDOM from 'react-dom/client';

import App from "./App";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<!-- index.html file
React application is built based on the following HTML document
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

React Components: Function Components and Class Components

A React component is a reusable, self-contained building block that defines the structure of a specific part of a user interface. Components can be functional or class-based and are at the core of React's component-based architecture. The components are rendered to a root element in the DOM using the React DOM library.

The two primary ways of declaring components in React are function components and class components. In older React code bases, you may find Class components primarily used. Function components, coupled with Hooks, have become the recommended approach for building React applications which were introduced in React 16.8.

Function Component

Function components are declared with a function (using JavaScript function syntax or an arrow function expression) that accepts a single “props” argument and returns JSX.

Below is an example of a function component in React,

// Function Syntax
function App() {
return (
<div>
<h1>Welcome to My React App!</h1>
<p>Let's start building amazing things.</p>
</div>
);
}

// Arrow function expression
const App = () => {
return (
<div>
<h1>Welcome to My React App!</h1>
<p>Let's start building amazing things.</p>
</div>
);
};

Rendering a Component

Now your React application has a component called App, which returns an <h1> and <p> element. To use this component in your application, use a similar syntax as normal HTML: <App />

import React from 'react';
import ReactDOM from 'react-dom/client';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Nesting components

React allows you to nest one component into another, allowing for the creation of complex user interfaces.

function MyButton() {
return (
<button>I'm a button</button>
);
}

/** Nested component */
export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}

Notice that <MyButton /> starts with a capital letter. That’s how to identify a React component. React components should always begin with a capital letter because React treats components starting with a lowercase letter as regular HTML elements. By using a capital letter for component names, React can differentiate between custom components and built-in HTML elements, ensuring proper rendering and behavior in the application.

In the code above, MyButton and MyApp are both React components. MyButton is called inside the MyApp component. You can declare multiple components in a file or different files and call as many different components in a component.

Class components

Class components are declared using ES6 classes. Class components in React behave similarly to function components. However, instead of using Hooks, class components utilize lifecycle methods provided by React to manage component state and lifecycle events, they use the lifecycle methods on React.Component base class. When you create a class component in React, you extend the base class React.Component, which allows your component to inherit and utilize the functionalities and lifecycle methods provided by React.Component, enabling you to control and manage the component’s state, props, and behavior effectively.

In a class component, the render() method is a mandatory requirement, this method returns HTML.

class App extends React.Component {
render() {
return (
<div>
<p>Header</p>
<p>Content</p>
<p>Footer</p>
</div>
);
}
}

Styling React Components

There are various approaches to styling React components with CSS

  1. Inline Styling

When applying inline styles to a React element using the style attribute, the value must be a JavaScript object containing key-value pairs where the keys represent the CSS properties, and the values represent the corresponding styles in camelCase format.

const App = () => {
return (
<div>
<h1 style={{ color: "white",
background: "blue",
padding: "10px",
width: "200px",
display: "flex",
justifyContent: "center",
alignItems: "center",
borderRadius: "10px"
}}>Welcome</h1>
<h2 style={{ color: "red", alignItems: "center" }}>React is fun!</h2>
</div>
)
};

export default App;

In this example, the first curly braces { } are used to add JavaScript expression with HTML syntax. The styles are passed are passed as object literals directly within the JSX code.

Each declaration includes a CSS property name and a value (name: value pair), separated by a colon. To include multiple CSS declarations, you separate them with semicolons, and the entire style block is enclosed within curly braces {}.

Note CSS properties must be written in camelCase syntax, where the first word is in lowercase and subsequent words start with uppercase letters, without any hyphens. This is different from the traditional hyphen-separated syntax used in regular CSS. For example, in regular CSS, you would write “background-color”, but in React inline styles, it would be “backgroundColor”.

2. JavaScript Object

The styles are written as JavaScript objects with properties to define the styles. you create a JavaScript object containing the styling information, and then refer to this object in the style attribute of the corresponding JSX element.


const App = () => {
const myStyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Sans-Serif"
};

return (
<div>
<h1 style={myStyle}>Hello React!</h1>
<p>Adding style!</p>
</div>
);
}
export default App;

myStyle is a JavaScript object with styles as properties. The name-value pairs in the JavaScript object represent CSS property names and values. You add the style using the style attribute with a JavaScript expression as the value. The object name is passed as the expression in the curly braces {}.

3. CSS Stylesheet

You write your CSS styling in a separate file by saving it with the .css file extension. Once you have created the CSS file, you can then import it into your React application, and the styles defined in the CSS file will be applied to the corresponding components.

/* App.css file */
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Arial;
}

.button {
color: DodgerBlue;
padding: 40px;
text-align: center;
}
/** App.js file */
import './App.css';

export default function MyApp() {
return (
<div>
<h1 className={styles.button}>Welcome to my app</h1>
</div>
);
}
/** index.js file */
import React from 'react';
import ReactDOM from 'react-dom/client';
import MyApp from './App.js';

ReactDOM.render(<MyApp />, document.getElementById('root'));

Here, the style is written in the App.css file in the same directory as the React App.js and index.js files. the styles are imported in the App.js file. The class name for an element is declared in curly braces { } as a JavaScript expression i.e., styles.button.

React Hooks

React introduced Hooks in version 16.8, and they serve as functions that enable developers to “hook into” React’s state and lifecycle features from functional components.

Hooks allow function components to have access to state and other React features. With the introduction of Hooks, class components are no longer the only option for managing state and lifecycle in React applications. React provides several built-in Hooks such as useState, useContext, useCallback, useEffect, useRef, useMemo, and useReducer.

Rules of hooks
he two rules of Hooks in React are essential to ensure that Hooks work correctly and consistently in function components:

  • Hooks Can Only be Called Inside React Function Components: Hooks should be used only within React function components and not in regular JavaScript functions or class components.
  • Hooks Can Only be Called at the Top Level of a Component: Hooks should be called at the top level of a function component, meaning they should not be called inside loops, conditions, or nested statements. This ensures that Hooks are executed in the same order on each render
  • Hooks cannot be conditional: Hooks cannot be conditionally called, meaning they cannot be placed inside if statements or other conditional structures

Here’s an example of how React hook works using useState. This creates a component that increments a count when a button is clicked.

import { useState } from 'react'

function App() {
const [counter, setCounter] = useState(0);

const increment = () => {
setCounter(counter + 1);
};

return (
<div className="App">
<button onClick={increment}>Click me</button>
<h2>{`Button clicked ${counter} times`}</h2>
</div>
);
}

export default App;

In the above code, we import the useState hook from React. By calling useState(0), we initialize the counter state variable with a value of 0 and the setCounter function to update it. The increment function is called when the button is clicked, updating the count.

useState accepts an initial state and returns two values: The current state, A function that updates the state. Notice that we are destructuring the returned values from useState. React synchronizes the user interface each time the state changes.

output for the example on useState

After the button clicked…

Variables and props

Variables

As I have mentioned earlier in the article, curly braces { } are used to hold JavaScript expressions. Variables are expressions. To store a value in a variable and use it in components, declare the variable, then pass the variable as expressions when needed.

function App() {
const text = "React";

return (
<div className="App">
<h1>Hello, {text}!</h1>
<p style={{ color: "blue", alignItems: "center" }}>{text} is fun</p>
</div>
);
}


/** output:
Hello, React!
React is fun */

React Props

Props are arguments passed into React components. In React, props (short for “properties”) are used to pass data from one component to another. When rendering a component, you can pass values to it through HTML attributes, which are then accessible within the component as props.

React Props behave similarly to function arguments in JavaScript and attributes in HTML.

To send props into a component, use the same syntax as HTML attributes. The props are added as values of the attributes in the React component. In the example below, “button” is the argument assigned to the attribute name text in MyButton component

const myElement =  <MyButton text="button"/>

When a component receives props, it receives them as a single object known as the props object.

function MyButton(props) {
return (
<button>I'm a { props.text }!</button>
);
}

Here, props is an object. This object contains all the key-value pairs of the props passed to the component.

To access the values, you can either use

  • Dot notation ( props.text )
  • Square bracket notation ( props[“text”] )
  • Destructure the object. ( const { text } = props )
function MyButton({text, text2}) {
return (
<button>`I'm a {text}, {text2}`</button>
);
}

export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton text="button" text2="Click me"/>
</div>
);
}

Lists and conditional rendering

React enables dynamic rendering of lists and conditional rendering of components based on specific conditions, making it easy to build flexible and interactive user interfaces.

Lists

React allows you to dynamically render lists of elements by using JavaScript’s map() function along with JSX.

function ItemList() {
const items = ['Car', 'Bag', 'Shoe'];
return (
<>
<h1>What do you have?"</h1>
<ul>
{items.map((item) => <li>{item}</li>)}
</ul>

<ul>
{items.map((item, index) => (
<li key={item}>{index}. {item}</li>
))}
</ul>
</>
);
}

Conditionals

React allows you to conditionally render components based on specific conditions using regular JavaScript expressions within JSX.

function Pass() {
return <h1>Pass!</h1>;
}

function Fail() {
return <h1>Failed!</h1>;
}
  • if statement
export default function Result() {
const status = true;
if (status) {
return <Pass />;
}
return <Fail />;
}
  • Ternary Operator

Check out my article on Ternary Operator

export default function Result() {
const status = true;
return (
<>
{ status ? <Pass /> : <Fail /> }
</>
);
}

Here’s an example of lists with objects:

function Student(props) {
return <li>I scored { props.score }</li>;
}

function Result() {
const Scores = [
{id: 1, Grade: 70},
{id: 2, Grade: 98},
{id: 3, Grade: 45}
];
return (
<>
<h1>What are the students score?</h1>
<ul>
{cores.map((score) => <Student key={score.id} brand={score.rade} />)}
</ul>
</>
);
}

JSX — JavaScript + XML

JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together. SX is a syntax extension for JavaScript that allows developers to write HTML elements in JavaScript code.

React takes care of rendering JSX into the DOM (Document Object Model). JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element. className is used instead of class for adding CSS classes, as class is a reserved keyword in JavaScript. Properties and methods in JSX are written in camelCase.

const Text = <h1 className="myclass">I Love JSX!</h1>;

const myElement = (
<div>
<Text />
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</div>
);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);

Resources

React Crash Course

Conclusion

By following this step-by-step guide, you’ve acquired a solid foundation in React development. Remember that practice and hands-on experience are key to mastering React. Keep building projects, and exploring additional resources.

If you like the article and would like to support me, make sure to:

👏 Clap for the story (claps)
🔔 Share and Follow me on Medium

🔔 Send me a DM on Twitter

--

--

preciousvictory

Frontend Developer || Technical writer || Passionate about tech and learning new things 💻✨