Thursday, June 27, 2024

React JS props with Class Component

How can we use Props with Class Component?

In React, class components can receive data from their parent components using props. Here's how you can use props with class components:

1. Define Props in Class Component:

Inside your class component, you can access props using 'this.props'. Props are passed to the constructor as the first argument or directly accessed within class methods.

   import React, { Component } from 'react';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

2. Pass Props from Parent Component:

When rendering a class component, you can pass props to it as attributes.

   import React, { Component } from 'react';
   import MyComponent from './MyComponent';

   class ParentComponent extends Component {
     render() {
       return <MyComponent message="Hello, world!" />;
     }
   }

3. Access Props Inside Class Component:

Once props are passed, you can access them inside the class component using 'this.props'.

   import React, { Component } from 'react';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

In this example, 'this.props.message' will render "Hello, world!".

4. Default Props:

You can also define default values for props using the 'defaultProps' static property.

   import React, { Component } from 'react';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

   MyComponent.defaultProps = {
     message: 'Default message'
   };

If 'message' prop is not provided when using 'MyComponent', it will default to "Default message".

Using props with class components allows you to pass data down the component hierarchy and make your components more dynamic and reusable.

No comments:

Post a Comment

Hot Topics