DEV Community

Cover image for Components in React
Mahalakshmi C
Mahalakshmi C

Posted on

Components in React

  • A component is a reusable and independent part of a user interface in React.
  • Components help divide a large application into smaller and manageable parts.

For example, a website can be divided into components such as:

  • Navbar
  • Header
  • Home
  • Product
  • Footer
  • Login Form

Each component can have its own structure and behavior.

Why Are Components Used?

Components provide several benefits:

  • Reusability
  • Easy Maintenance
  • Separation of UI
  • Passing Data - Props are used to pass data from one component to another.

Types of Components

React components are mainly written as functional components in modern React.

Functional Component

A functional component is a JavaScript function that returns JSX.

function App() {
    return (
        <div>
            <Welcome />
            <p>This is my React application.</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

App is the main component, and Welcome is used inside App.

Class Components

Class components are an older way of creating React components.

class Welcome extends React.Component {
    render() {
        return <h1>Hello React</h1>;
    }
}
Enter fullscreen mode Exit fullscreen mode

Class components were commonly used before Hooks were introduced.

Example for components

function BlogPost() {
    return (
        <article>
            <h2>Introduction to React</h2>
            <p>
                React is a JavaScript library used to build
                user interfaces.
            </p>
        </article>
    );
}

function App() {
    return (
        <div>
            <h1>My Blog</h1>

            <BlogPost />
            <BlogPost />
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

How Does This Work?

The BlogPost component contains the UI for one blog post.

Inside the App component:

<BlogPost />
<BlogPost />

the same component is used twice.

Therefore, React displays two blog posts without writing the same HTML/JSX code again.

My Blog

Introduction to React
React is a JavaScript library used to build user interfaces.

Introduction to React
React is a JavaScript library used to build user interfaces.

Enter fullscreen mode Exit fullscreen mode

Conclusion

Components are a fundamental part of React. They allow an application to be divided into small, reusable, and manageable pieces. By combining different components, a complete React application can be created.

Top comments (0)