Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - React

Introduction to React.js

React.js is a popular JavaScript library for building user interfaces, particularly single-page applications where data changes over time. This tutorial introduces you to the basics of React.js, including components, state, props, and the component lifecycle.

Key Points:

  • React is a component-based library for building user interfaces.
  • Components can be functional or class-based.
  • State and props are used to manage data and pass it between components.
  • The component lifecycle consists of mounting, updating, and unmounting phases.

Setting Up a React Project

To get started with React, you can use Create React App, a tool that sets up a new React project with a sensible default configuration.


// Create a new React project
npx create-react-app my-react-app

// Navigate to the project directory
cd my-react-app

// Start the development server
npm start
                

Understanding Components

Components are the building blocks of a React application. They can be either functional or class-based. Here's an example of both:

Functional Component


// src/FunctionalComponent.js
import React from 'react';

const FunctionalComponent = () => {
    return <div>Hello from Functional Component!</div>;
};

export default FunctionalComponent;
                

Class Component


// src/ClassComponent.js
import React, { Component } from 'react';

class ClassComponent extends Component {
    render() {
        return <div>Hello from Class Component!</div>;
    }
}

export default ClassComponent;
                

Using State and Props

State and props are essential concepts in React for managing data and passing it between components. State is managed within a component, while props are passed from parent to child components.

State Example


// src/StateComponent.js
import React, { useState } from 'react';

const StateComponent = () => {
    const [count, setCount] = useState(0);

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
};

export default StateComponent;
                

Props Example


// src/PropsComponent.js
import React from 'react';

const PropsComponent = ({ message }) => {
    return <div>Message: {message}</div>;
};

export default PropsComponent;

// src/App.js (using PropsComponent)
import React from 'react';
import PropsComponent from './PropsComponent';

const App = () => {
    return <div>
        <PropsComponent message="Hello, World!" />
    </div>;
};

export default App;
                

Component Lifecycle

React components go through a lifecycle of mounting, updating, and unmounting. Class components have special methods that can be used to perform actions at different stages of the lifecycle.


// src/LifecycleComponent.js
import React, { Component } from 'react';

class LifecycleComponent extends Component {
    componentDidMount() {
        console.log('Component did mount');
    }

    componentDidUpdate(prevProps, prevState) {
        console.log('Component did update');
    }

    componentWillUnmount() {
        console.log('Component will unmount');
    }

    render() {
        return <div>Lifecycle Component</div>;
    }
}

export default LifecycleComponent;
                

Handling Events

React provides a way to handle events such as clicks, form submissions, and more. Event handlers in React are written using camelCase syntax.


// src/EventHandlingComponent.js
import React from 'react';

const EventHandlingComponent = () => {
    const handleClick = () => {
        alert('Button clicked!');
    };

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

export default EventHandlingComponent;
                

Conditional Rendering

Conditional rendering in React allows you to render different UI elements based on certain conditions.


// src/ConditionalRenderingComponent.js
import React, { useState } from 'react';

const ConditionalRenderingComponent = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    return (
        <div>
            {isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
            <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
                {isLoggedIn ? 'Log Out' : 'Log In'}
            </button>
        </div>
    );
};

export default ConditionalRenderingComponent;
                

Lists and Keys

Rendering lists of data in React involves using the map function. Each item in the list should have a unique key prop.


// src/ListComponent.js
import React from 'react';

const ListComponent = () => {
    const items = ['Item 1', 'Item 2', 'Item 3'];

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

export default ListComponent;
                

Summary

In this tutorial, you learned about the basics of React.js, including setting up a React project, understanding components, using state and props, handling the component lifecycle, managing events, implementing conditional rendering, and rendering lists with keys. React is a powerful library for building dynamic user interfaces, and mastering these concepts will help you create robust and efficient applications.