get static props

What are Static Props in React?

Static Props in React are the properties that are passed down from a parent component to a child component in a read-only manner. These props cannot be modified by the child component, and are used to pass data and functionality from parent to child components.

How to get Static Props in React?

In order to get Static Props in React, we need to pass them down from the parent component to the child component using the props parameter. We can define the static props in the parent component and then pass them down to the child component as shown below:


// Parent Component
class ParentComponent extends React.Component {
  render() {
    const staticProps = {
      name: "John",
      age: 30
    };
    
    return (
      <ChildComponent {...staticProps} />
    );
  }
}

// Child Component
class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        <p>Name: {this.props.name}</p>
        <p>Age: {this.props.age}</p>
      </div>
    );
  }
}

In the example above, we define a staticProps object in the ParentComponent and then pass it down to the ChildComponent using the spread operator. The ChildComponent then uses these static props to display the name and age of the person.

Another way to get static props is by using the PropTypes library. We can define the static props in the parent component and then use PropTypes to validate them in the child component as shown below:


import PropTypes from 'prop-types';

// Parent Component
class ParentComponent extends React.Component {
  static propTypes = {
    name: PropTypes.string,
    age: PropTypes.number
  };
  
  render() {
    const staticProps = {
      name: "John",
      age: 30
    };
    
    return (
      <ChildComponent {...staticProps} />
    );
  }
}

// Child Component
class ChildComponent extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired
  };
  
  render() {
    return (
      <div>
        <p>Name: {this.props.name}</p>
        <p>Age: {this.props.age}</p>
      </div>
    );
  }
}

In this example, we define the static props in the ParentComponent and then use PropTypes to validate them in the ChildComponent. PropTypes will throw a warning if the static props are not passed down or if they are of the wrong type.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe