Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

React - Functional Components

Creating and using functional components

Functional components are the simplest way to define a component in React. They are JavaScript functions that return JSX and are primarily used for presenting data. This tutorial covers how to create and use functional components in React.

Key Points:

  • Functional components are JavaScript functions that return JSX.
  • They do not have their own state or lifecycle methods (use hooks for state and lifecycle).
  • Functional components are often used for rendering static content or simple UIs.

Defining a Functional Component

To define a functional component, create a JavaScript function that returns JSX. Functional components receive props as an argument.

// Functional component example
import React from 'react';

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

export default Welcome;

In this example, the Welcome component renders a greeting message using the name prop.

Using Props in Functional Components

Props are used to pass data from parent components to child components. In functional components, props are passed as an argument to the function.

// Using props in a functional component
import React from 'react';

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

export default Welcome;

// Using the Welcome component
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome from './Welcome';

ReactDOM.render(<Welcome name="John" />, document.getElementById('root'));

Using Hooks in Functional Components

Hooks allow you to use state and other React features in functional components. The most commonly used hooks are useState and useEffect.

useState Hook

The useState hook allows you to add state to functional components.

// Using useState in a functional component
import React, { useState } from 'react';

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

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

export default Counter;

useEffect Hook

The useEffect hook allows you to perform side effects in functional components, such as fetching data or subscribing to events.

// Using useEffect in a functional component
import React, { useEffect, useState } from 'react';

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

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

    return (
        <div>
            {data ? <p>Data: {data}</p> : <p>Loading...</p>}
        </div>
    );
}

export default DataFetcher;

Passing Functions as Props

Functions can be passed as props to functional components, allowing child components to communicate with parent components.

// Passing functions as props
import React from 'react';

function Button(props) {
    return <button onClick={props.onClick}>Click me</button>;
}

function App() {
    const handleClick = () => {
        alert('Button clicked');
    };

    return <Button onClick={handleClick} />;
}

export default App;

Conditional Rendering

Functional components can perform conditional rendering based on their props or state.

// Conditional rendering in a functional component
import React, { useState } from 'react';

function Greeting() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

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

export default Greeting;

In this example, the Greeting component conditionally renders a message based on the isLoggedIn state.

Composing Functional Components

Functional components can be composed together to build complex user interfaces. This means you can use one component inside another, passing data down through props.

// Composing functional components
import React from 'react';

function App() {
    return (
        <div>
            <Welcome name="Alice" />
            <Welcome name="Bob" />
            <Welcome name="Charlie" />
        </div>
    );
}

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

export default App;

Summary

In this tutorial, you learned how to create and use functional components in React. Functional components are JavaScript functions that return JSX and are used for presenting data. You learned about defining functional components, using props, using hooks such as useState and useEffect, passing functions as props, conditional rendering, and composing functional components. Understanding functional components is essential for building modern React applications.