DEV Community

Gopal Adhikari
Gopal Adhikari

Posted on • Originally published at gopaladhikari.hashnode.dev

React JS: A Comprehensive Guide

React JS, commonly referred to as React, is a powerful JavaScript library for building user interfaces, particularly for single-page applications. Developed and maintained by Facebook, React allows developers to create large web applications that can update and render efficiently in response to data changes. This article will provide an in-depth look at React, its core concepts, and how to get started with building applications using this library.

What is React?

React is a library for building user interfaces from individual pieces called components. These components can be combined to create complex UIs. React is designed to be simple, declarative, and component-based, making it easier to build and maintain large applications.

Key Features of React

  1. Component-Based Architecture: React applications are built using components, which are self-contained modules that encapsulate their own structure, logic, and styling.

  2. JSX: React uses JSX, a syntax extension that allows you to write HTML-like code within JavaScript. This makes the code more readable and easier to write.

  3. Virtual DOM: React uses a virtual DOM to optimize updates and rendering. When the state of an object changes, React updates the virtual DOM first, then compares it with the real DOM, and finally updates only the parts that have changed.

  4. Unidirectional Data Flow: React enforces a one-way data flow, making it easier to understand and debug applications.

  5. Hooks: Introduced in React 16.8, hooks allow you to use state and other React features without writing a class.

Getting Started with React

Prerequisites

Before you start with React, you should have a basic understanding of HTML, CSS, and JavaScript. Familiarity with ES6 features like classes, modules, and arrow functions will also be beneficial.

Setting Up a React Environment

To set up a React development environment, you need Node.js and npm (Node Package Manager) installed on your machine. You can download and install Node.js from nodejs.org.

Once Node.js is installed, you can create a new React application using Create React App, a tool that sets up a new React project with a sensible default configuration.

npx create-react-app my-app
cd my-app
npm start
Enter fullscreen mode Exit fullscreen mode

This will create a new directory called my-app with all the necessary files and dependencies. The npm start command will start a development server and open your new React application in the browser.

Creating and Nesting Components

React applications are made up of components. A component is a piece of the UI that has its own logic and appearance. Components can be as small as a button or as large as an entire page.

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

export default function MyApp() {
  return (
    <div>
      <h1>Welcome to my app</h1>
      <MyButton />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Writing Markup with JSX

JSX is a syntax extension that allows you to write HTML-like code within JavaScript. It is optional but widely used in React projects for its convenience.

function AboutPage() {
  return (
    <>
      <h1>About</h1>
      <p>Hello there.<br />How do you do?</p>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Adding Styles

In React, you specify a CSS class with className. It works the same way as the HTML class attribute.

<img className="avatar" />
Enter fullscreen mode Exit fullscreen mode

Then you write the CSS rules for it in a separate CSS file:

/* In your CSS */
.avatar {
  border-radius: 50%;
}
Enter fullscreen mode Exit fullscreen mode

Displaying Data

JSX lets you put markup into JavaScript. Curly braces allow you to embed JavaScript expressions within JSX.

const user = {
  name: 'Hedy Lamarr',
  imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
  imageSize: 90,
};

export default function Profile() {
  return (
    <>
      <h1>{user.name}</h1>
      <img
        className="avatar"
        src={user.imageUrl}
        alt={'Photo of ' + user.name}
        style={{
          width: user.imageSize,
          height: user.imageSize,
        }}
      />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conditional Rendering

In React, you can use JavaScript techniques like if statements and the conditional (?) operator to conditionally render elements.

let content;
if (isLoggedIn) {
  content = <AdminPanel />;
} else {
  content = <LoginForm />;
}
return <div>{content}</div>;
Enter fullscreen mode Exit fullscreen mode

Rendering Lists

You can use JavaScript features like the map() function to render lists of components.

const products = [
  { title: 'Cabbage', id: 1 },
  { title: 'Garlic', id: 2 },
  { title: 'Apple', id: 3 },
];

const listItems = products.map(product =>
  <li key={product.id}>
    {product.title}
  </li>
);

return <ul>{listItems}</ul>;
Enter fullscreen mode Exit fullscreen mode

Responding to Events

You can respond to events by declaring event handler functions inside your components.

function MyButton() {
  function handleClick() {
    alert('You clicked me!');
  }
  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Using Hooks

Hooks are functions that let you use state and other React features in functional components. The useState hook is used to add state to a component.

import { useState } from 'react';

function MyButton() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      Clicked {count} times
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Sharing Data Between Components

To share data between components, you can lift the state up to the closest common ancestor and pass it down as props.

import { useState } from 'react';

export default function MyApp() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counters that update together</h1>
      <MyButton count={count} onClick={handleClick} />
      <MyButton count={count} onClick={handleClick} />
    </div>
  );
}

function MyButton({ count, onClick }) {
  return (
    <button onClick={onClick}>
      Clicked {count} times
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

React is a powerful and flexible library for building user interfaces. Its component-based architecture, JSX syntax, and unidirectional data flow make it a popular choice for developers. By understanding the core concepts and getting hands-on experience with building components, you can start creating dynamic and efficient web applications with React. For more detailed information and advanced topics, refer to the official React documentation.

Top comments (0)