Contents

Creating Components

Creating and styling components in React involves breaking down the UI into reusable pieces, managing state and props to control the behavior and appearance of these components, and applying styles to make them visually appealing.

Creating and Styling Components

Step 1: Creating Components

React components can be created as either function components or class components. Function components are more concise and are preferred in modern React development, especially with the introduction of hooks.

Function Component Example:

				
					// components/Header.js
import React from 'react';

function Header() {
  return (
    <header>
      <h1>Task Manager</h1>
    </header>
  );
}

export default Header;


				
			

Class Component Example:

				
					// components/Footer.js
import React, { Component } from 'react';

class Footer extends Component {
  render() {
    return (
      <footer>
        <p>&copy; 2024 Task Manager Inc.</p>
      </footer>
    );
  }
}

export default Footer;


				
			

Step 2: Styling Components

You can style components using CSS, inline styles, CSS modules, or styled-components. Here’s an example of styling components using CSS:

CSS File:

				
					/* styles/Header.css */
header {
  background-color: #282c34;
  padding: 20px;
  color: white;
  text-align: center;
}

				
			

Applying CSS in Component:

				
					// components/Header.js
import React from 'react';
import './styles/Header.css';

function Header() {
  return (
    <header className="Header">
      <h1>Task Manager</h1>
    </header>
  );
}

export default Header;


				
			

Using CSS Modules:

CSS Modules allow you to scope CSS to a specific component, avoiding global namespace pollution.

Example:

CSS Module File:

				
					/* styles/Header.module.css */
.header {
  background-color: #282c34;
  padding: 20px;
  color: white;
  text-align: center;
}


				
			

Applying CSS Module in Component:

				
					// components/Header.js
import React from 'react';
import styles from './styles/Header.module.css';

function Header() {
  return (
    <header className={styles.header}>
      <h1>Task Manager</h1>
    </header>
  );
}

export default Header;


				
			

Managing State and Props

State Management

State is used to manage data that can change over time within a component. It is typically used for storing user input, dynamic data, and component-specific information.

Example:

				
					// components/TaskList.js
import React, { useState } from 'react';

function TaskList() {
  const [tasks, setTasks] = useState([
    { id: 1, title: 'Task 1', completed: false },
    { id: 2, title: 'Task 2', completed: false },
  ]);

  const toggleTaskCompletion = (taskId) => {
    setTasks(
      tasks.map((task) =>
        task.id === taskId ? { ...task, completed: !task.completed } : task
      )
    );
  };

  return (
    <div>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task) => (
          <li key={task.id}>
            <input
              type="checkbox"
              checked={task.completed}
              onChange={() => toggleTaskCompletion(task.id)}
            />
            {task.title}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TaskList;


				
			

In this example, the TaskList component manages a list of tasks in its state and provides a way to toggle the completion status of each task.

Props Management

Props are used to pass data from parent components to child components. They are read-only and help in configuring child components.

Example:

				
					// components/TaskItem.js
import React from 'react';

function TaskItem({ task, onToggle }) {
  return (
    <li>
      <input
        type="checkbox"
        checked={task.completed}
        onChange={() => onToggle(task.id)}
      />
      {task.title}
    </li>
  );
}

export default TaskItem;


				
			

Using TaskItem Component in TaskList:

				
					// components/TaskList.js
import React, { useState } from 'react';
import TaskItem from './TaskItem';

function TaskList() {
  const [tasks, setTasks] = useState([
    { id: 1, title: 'Task 1', completed: false },
    { id: 2, title: 'Task 2', completed: false },
  ]);

  const toggleTaskCompletion = (taskId) => {
    setTasks(
      tasks.map((task) =>
        task.id === taskId ? { ...task, completed: !task.completed } : task
      )
    );
  };

  return (
    <div>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task) => (
          <TaskItem key={task.id} task={task} onToggle={toggleTaskCompletion} />
        ))}
      </ul>
    </div>
  );
}

export default TaskList;

				
			

In this example, the TaskList component passes each task and the toggleTaskCompletion function to the TaskItem component via props.

Conclusion

Creating and styling components in React involves defining reusable function or class components, managing state within these components, and passing data through props. By organizing your components and styles effectively, you can create a modular and maintainable codebase. Managing state and props efficiently allows for dynamic and interactive user interfaces. Next, we’ll explore implementing features such as routing, CRUD operations, and integrating with external APIs in your React application.