React 101: Learn to Start with React

101 React

Hello there, fellow coder! Welcome to this exciting journey where we’ll explore the world of React, a JavaScript library that has revolutionized the way we build web applications. If you’re excited about creating interactive UIs with ease, you’re in the right place.

Brief Overview of React

React, often referred to as React.js or ReactJS, is an open-source JavaScript library for building dynamic user interfaces. It was developed by Facebook in 2013 and has since gained massive popularity in the developer community. One of the reasons why React stands out from other JavaScript libraries is because of its component-based architecture. This means you can build encapsulated components that manage their own state, and then compose them to make complex UIs.

Here’s a simple example of a React component:

import React from 'react';

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

// To use it in HTML
<Welcome name="Sarah" />

In this example, Welcome is a React component that accepts a name as a prop and renders a greeting message. The beauty of this is that the Welcome component can be reused anywhere in your application, and it will always render what’s inside of its render method.

React also shines when it comes to updating the UI and handling changes in state. It uses a virtual DOM (Document Object Model) to keep track of changes in an application’s state. When the state of a component changes, React updates only the components that depend on that state, instead of reloading the entire page. This makes React applications incredibly fast and efficient.

In the upcoming sections, we’ll dive deeper into these concepts and explore what truly makes React special. So, stick around, and let’s embark on this exciting journey together!

What Makes React Special

React is a unique library in the JavaScript ecosystem, and it’s not just because of its popularity. It’s the combination of a number of features and concepts that make it stand out. Let’s delve deeper into these features.

Templating with JSX

JSX, or JavaScript XML, is a syntax extension for JavaScript. It might look like a template language, but it comes with the full power of JavaScript. JSX produces React “elements”, and these elements are the building blocks of any React application.

Understanding JSX

JSX allows us to write HTML-like syntax in our JavaScript code, which makes the code easier to understand and write. It’s not a necessity to use JSX when coding with React, but it’s recommended due to its simplicity.

Here’s a simple JSX syntax:

const element = <h1>Hello, world!</h1>;

In this example, we’re defining a constant called element and assigning it a JSX expression. This JSX expression looks like an HTML tag, but it’s actually JavaScript!

How JSX Works in React

JSX is not valid JavaScript, so it needs to be compiled into JavaScript. This is done using Babel, a JavaScript compiler. Babel transforms the JSX into React.createElement() function calls.

For example, the JSX code:

const element = <h1>Hello, world!</h1>;
// is compiled to:
const element = React.createElement('h1', null, 'Hello, world!');

This is what the browser will interpret and use to display content on the screen.

Classes or Hooks

React offers two ways to define components: class components and function components. Initially, only class components could have state and lifecycle methods, but with the introduction of Hooks in React 16.8, function components can now use these features too.

The Concept of Classes in React

Class components are ES6 classes that extend React.Component. They must have a render method that returns JSX. The state of the component is stored in this.state and can be updated using this.setState().

Here’s an example of a class component:

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: 'Sarah' };
  }

  render() {
    return <h1>Hello, {this.state.name}</h1>;
  }
}

In this example, Welcome is a class component that has a state with a property name. The render method returns a JSX expression that displays a greeting message.

The Concept of Hooks in React

Hooks are functions that let you “hook into” React state and lifecycle features from function components. The two main hooks are useState and useEffect.

Here’s how you could write the previous example with a function component and a hook:

import React, { useState } from 'react';

function Welcome() {
  const [name, setName] = useState('Sarah');

  return <h1>Hello, {name}</h1>;
}

In this example, Welcome is a function component that uses the useState hook to create a state variable name and a function setName to update it.

Comparing Classes and Hooks

Class components are more verbose and complex, but they are also more flexible and powerful. They are a good choice for larger, more complex components.

Hooks, on the other hand, are simpler and easier to understand. They are a great choice for smaller, simpler components, and they can make your code cleaner and easier to read.

Component Hooks

Hooks are a new addition in React 16.8 that allow you to use state and other React features without writing a class. The two main hooks you’ll use are useState and useEffect.

Understanding Component Hooks

useState is a Hook that lets you add React state to function components. Here is how you can use it:

const [age, setAge] = useState(42);

In the above example, useState is called with the initial state as an argument (42 in this case). It returns a pair of values: the current state (age) and a function that updates it (setAge).

useEffect, on the other hand, lets you perform side effects in function components. Side effects are operations that affect other components, such as data fetching, subscriptions, or manual DOM manipulations.

Different Types of Component Hooks

While useState and useEffect are the most commonly used hooks, React provides a few built-in hooks like useContext, useReducer, useCallback, useMemo, and useRef.

Using Effects

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

Here’s how you use it:

useEffect(() => {
  document.title = `You clicked ${count} times`;
});

In this example, the useEffect hook takes a function as an argument, and this function runs after every render.

The useEffect Hook

useEffect is incredibly powerful. For example, you can use it to fetch data:

const [data, setData] = useState(null);

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []);

In this example, we’re using useEffect to fetch data from an API and store it in state.

Practical Examples of useEffect

useEffect is perfect for performing operations that are too “heavy” to run on every render, or that need to run after the component has updated. This includes things like setting up a subscription, fetching data, or updating the document title.

Combining useEffect with useState

useState and useEffect are often used together. You might use useState to declare a state variable, and useEffect to update that state in response to a change in props or state.

The useState Hook

useState is a function that lets you add state to your function components. It takes one argument, the initial state, and returns an array with two elements: the current state and a function to update it.

Here’s an example of how you might use useState:

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’re using useState to create a state variable count and a function setCount to update it. Then, we’re using these in our JSX to display the count and update it when a button is clicked.

How to Combine useEffect and useState

useEffect and useState are often used together. useState gives you a way to add state to your function components, and useEffect lets you interact with that state in response to component lifecycle events.

Building with React

Building applications with React is a joy due to its declarative nature and powerful features. Let’s explore some of these features and how they can be used to build complex user interfaces.

Creating Custom Event Triggers

In React, we can create custom events to handle user interactions or other dynamic changes in the application. These events can be triggered based on user actions like clicking a button, submitting a form, or even scrolling the page.

Understanding Event Triggers

Event triggers are essentially functions that are called in response to specific events. In React, these are often event handler functions that are passed as props to React elements.

How to Create Custom Event Triggers

Creating a custom event trigger in React is as simple as defining a function and passing it as a prop to a React element. Here’s an example:

function App() {
  const handleClick = () => {
    console.log('Button clicked!');
  };

  return <button onClick={handleClick}>Click me</button>;
}

In this example, we’ve defined a handleClick function that logs a message to the console. We then pass this function as a prop to a button element. When the button is clicked, the handleClick function is called.

Building a Modal

A modal is a dialog box or popup window that is displayed on top of the current page. Modals are used to command user interaction before they can return to the system.

What is a Modal?

In the context of a React application, a modal is a component that is conditionally rendered based on some piece of state. It often includes a form or other interactive elements and is used to gather input from the user or display important information.

Steps to Build a Modal in React

Building a modal in React involves a few steps:

  1. Create a new component for the modal.
  2. Add state to the parent component to track whether the modal is open.
  3. Render the modal component conditionally based on this state.
  4. Pass a function to the modal component to update the state when the modal should be closed.

Refactoring Data

As your React application grows, you might find that your components become bloated and difficult to manage. This is where refactoring comes in.

The Importance of Refactoring

Refactoring is the process of restructuring your code without changing its external behavior. It’s an essential part of software development that helps keep your code clean, efficient, and easy to understand.

How to Refactor Data in React

In React, refactoring often involves breaking down large components into smaller, reusable components. It might also involve lifting state up to a common ancestor component or using context to share state between components.

Building a Navigation

Navigation is a crucial part of any application. In a React application, we often use a library like React Router to handle navigation.

Understanding Navigation in React

In React, we can create a navigation component that renders different components based on the current path. This is often done using a library like React Router, which provides components like BrowserRouter, Route, and Link to handle navigation.

Steps to Build a Navigation in React

Here’s a basic example of how you might set up navigation in a React application using React Router:

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </nav>

      <Route path="/" exact component={Home} />
      <Route path="/about" component={About} />
    </Router>
  );
}

In this example, we’re using Router to set up a router, Link to create navigation links, and Route to render different components based on the current path.

Adding Buttons to Your Modals

Buttons play a crucial role in modals. They’re often used to submit forms, confirm actions, or close the modal.

The Role of Buttons in Modals

In a modal, buttons are used to interact with the content. This might involve submitting a form, confirming an action, or simply closing the modal. The buttons in a modal should be clear and easy to understand.

How to Add Buttons to Modals

Adding a button to a modal in React is as simple as adding a button element within your modal component. Here’s an example:

function Modal({ onClose }) {
  return (
    <div className="modal">
      <h2>Modal Title</h2>
      <p>Modal content...</p>
      <button onClick={onClose}>Close</button>
    </div>
  );
}

In this example, we’re adding a “Close” button to the modal. When this button is clicked, the onClose function is called, which should update the state to close the modal.

Conclusion

React is a powerful and flexible JavaScript library for building user interfaces. Its component-based architecture and rich ecosystem make it a great choice for both new projects and integrating into existing ones. Whether you’re building a small widget or a large, complex web application, React has the tools and community support to help you succeed.

Throughout this article, we’ve explored the core concepts of React, how to build with React, and how to extend React with CSS, Sass, custom fonts, and icons. We’ve also discussed how to build and publish a React application. These concepts and techniques form the foundation of React development, but there’s always more to learn.

Here are some resources to help you continue your learning journey with React:

  1. React Official Documentation: The official React documentation is a comprehensive resource covering all aspects of React development.
  2. React Router: Learn more about building navigations in your React applications.
  3. Styled Components: A library for styling your components in React.
  4. Sass Official Documentation: Learn more about using Sass, a powerful CSS preprocessor.
  5. Font Awesome: A library for adding vector icons and social logos to your website.
  6. Create React App: A tool to create a new React application with a modern build configuration.
  7. Vercel: A platform for static sites and Serverless Functions.
  8. Netlify: A platform that offers hosting and serverless backend services for web applications and static websites.

Remember, the best way to learn is by doing. Try building your own projects with React, experiment with different libraries and tools, and don’t be afraid to make mistakes.

https://ahmedradwan.dev

Reach out if you want to join me and write articles with the nerds 🙂


© 2024 · Nerd Level Tech

Categories

Social Media

Stay connected on social media