React Components and Props

React Components and Props

ยท

4 min read

In the previous blog of the series we learn about JSX, you can read it here

Welcome to the beginner's guide to React components and props!

In this blog, we'll explore the fundamental building blocks of React applications and learn how to pass data between components using props. Whether you're new to React or need a refresher, we've got you covered.

Let's dive in!

Understanding React Components

React Components are the building blocks of any React application. They are responsible for rendering UI elements and encapsulating their logic.

There are two types of components: functional components and class components.

  • Functional Components: Functional components are simple, pure functions that take props as arguments and return JSX elements. They are easy to read and maintain.

Here's an example of a basic functional component:

    import React from 'react';

    const Greeting = () => {
      const name = "Harsh"; 

      return <h1>Hello, {name}!</h1>;
    };

    export default Greeting;
  • Class Components: Class components are more traditional in their syntax and provide additional features through lifecycle methods. Although they are gradually being replaced by functional components with hooks, it's good to understand them.

    Here's an example of a class component:

      import React, { Component } from 'react';
    
      class Counter extends Component {
        state = {
          count: 0,
        };
    
        render() {
          return <div>Count: {this.state.count}</div>;
        }
      }
    

Creating Functional Components

Functional components are favored for their simplicity and are widely used in modern React applications.

  • Syntax and Structure: Functional components are defined using the arrow function syntax, taking props as an argument and returning JSX elements.

  • State in Functional Components: Functional components can have a state using React Hooks. The most commonly used hook is useState.

    Here's a quick example of how to use it:

      import React, { useState } from 'react';
    
      const Counter = () => {
        const [count, setCount] = useState(0);
    
        return (
          <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
          </div>
        );
      };
    

Creating Class Components

While functional components are becoming more popular, understanding class components is still beneficial, especially when working with legacy code.

  • Syntax and Structure: Class components are defined using the class keyword and extend the React.Component class. They have a render() method, where you return the JSX to be rendered.

  • State in Class Components: State in class components is defined using the this.state object. To update the state, use this.setState()

Here's a quick example of how to use it:

    import React, { Component } from 'react';

    class SimpleCounter extends Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0,
        };
      }

      handleIncrement = () => {
        this.setState({ count: this.state.count + 1 });
      };

      render() {
        return (
          <div>
            <p>Count: {this.state.count}</p>
            <button onClick={this.handleIncrement}>Increment</button>
          </div>
        );
      }
    }

    export default SimpleCounter;

Props

Props allow you to pass data from a parent component to a child component.

  • Prop Types: React provides prop types, which enable you to validate the data passed to components, making debugging easier.

  • Passing Props from Parent to Child Components: To pass props, simply include the desired attributes when using a component.

    For example:

      const App = () => {
        return <Greeting name="John" />;
      };
    

Accessing Props in Components

Both functional and class components can access props.

  • Functional Components: Props are accessed directly as function arguments.

    For example:

      const Greeting = (props) => {
        return <h1>Hello, {props.name}!</h1>;
      };
    
  • Class Components: In class components, props are accessed through this.props.

    For example:

      class Greeting extends React.Component {
        render() {
          return <h1>Hello, {this.props.name}!</h1>;
        }
      }
    

Best Practices and Tips

  • Organize your components in a modular and reusable manner.

  • Use descriptive names for components and props to improve code readability.

  • Prefer functional components with hooks over class components for better readability and maintainability.

Conclusion

You should now have a solid understanding of React components and props. You can create functional and class components with ease and pass data between them using props. Keep practicing and learning.

I'll see you in the next one ๐Ÿ˜‰

Bye Bye ๐Ÿ‘‹

Did you find this article valuable?

Support Harsh's Insights by becoming a sponsor. Any amount is appreciated!

ย