DEV Community

Cover image for Day 3: React Components
Dipak Ahirav
Dipak Ahirav

Posted on

Day 3: React Components

Welcome to Day 3 of our React.js learning journey! Today, we will explore React components in more depth. Components are the building blocks of a React application, allowing you to create reusable and modular UI elements.

Understanding React Components

In React, everything is a component. Components are like custom HTML elements that encapsulate the UI logic and behavior. There are two main types of components in React: functional components and class components.

Functional Components

Functional components are JavaScript functions that return JSX elements. They are simple, lightweight, and easy to read. Here's an example of a functional component:

function Greeting() {
  return <h1>Hello, World!</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Class Components

Class components are ES6 classes that extend React.Component. They have additional features like state and lifecycle methods. Here's an example of a class component:

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

Creating and Rendering Components

To create and render components in React, you simply need to import them into your application and include them in your JSX code. Here's how you can render the Greeting component we defined earlier:

function App() {
  return (
    <div>
      <Greeting />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Props in React Components

Props (short for properties) allow you to pass data from a parent component to a child component. They are read-only and help make your components dynamic and reusable. Here's how you can pass a prop to a component:

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

function App() {
  return <Welcome name="Alice" />;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Today, you've delved deeper into React components, understanding the difference between functional and class components, creating and rendering components, and using props to make your components dynamic. Components are at the core of React development, enabling you to build complex UIs in a modular and scalable way.

In the upcoming days, we will explore more advanced React concepts, such as state management, hooks, and conditional rendering. Stay tuned for Day 4 of our React.js learning journey!

Top comments (1)

Collapse
 
dipakahirav profile image
Dipak Ahirav

Next part -> Day - 4