React Props

In React, Props (properties) are a mechanism for passing data from a parent component to a child component. Props are read-only; child components cannot directly modify them. Instead, the parent component should manage and update them.

The main difference between state and props ispropsProps are immutable, while state can change based on user interaction. This is why some container components need to define state to update and modify data. Child components can only pass data through props.


Using Props

Syntax for passing props:

<ComponentName propName={propValue} />

The following example demonstrates how to use props in a component:

React Example

function HelloMessage(props) { return <h1>Hello {props.name}!</h1>; } const element = <HelloMessage name="Example"/>; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( element );

Try it »

In the example, the name attribute is obtained via props.name.


Default Props

You can set default values for props using the component class's defaultProps property, as shown in the example:

React Example

class HelloMessage extends React.Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } HelloMessage.defaultProps = { name: 'Example' }; const element = <HelloMessage/>; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( element );

Try it »

Multiple Props

You can pass multiple properties to a child component.

Example

const UserCard = (props) => {
  return (
    <div>
      <h2>{props.name}</h2>
      <p>Age: {props.age}</p>
      <p>Location: {props.location}</p>
    </div>
  );
};

const App = () => {
  return (
    <UserCard name="Alice" age={25} location="New York" />
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

propTypes Validation

propTypes is a tool provided by React for type-checking component props.

You can use the prop-types library to perform type checking on component props.

In React, propTypes is defined as a static property of a component. First, you need to install the prop-types package:

npm install prop-types

Then, import prop-types in your component file and define the propTypes property. Here is an example:

Example

import PropTypes from 'prop-types';

const Greeting = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

Greeting.propTypes = {
  name: PropTypes.string.isRequired
};

const App = () => {
  return (
    <div>
      <Greeting name="Alice" />
      {/* <Greeting /> // This line will cause a console warning because name is required */}
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

Passing Callback Functions as Props

You can pass functions as props to child components, and child components can call these functions to communicate with the parent component.

Example

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: '' };
  }

  handleMessage = (msg) => {
    this.setState({ message: msg });
  };

  render() {
    return (
      <div>
        <ChildComponent onMessage={this.handleMessage} />
        <p>Message from Child: {this.state.message}</p>
      </div>
    );
  }
}

const ChildComponent = (props) => {
  const sendMessage = () => {
    props.onMessage('Hello from Child!');
  };

  return (
    <div>
      <button onClick={sendMessage}>Send Message</button>
    </div>
  );
};

ReactDOM.render(<ParentComponent />, document.getElementById('root'));

Destructuring Props

In function components, you can simplify code by destructuring props.

Example

const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

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

ReactDOM.render(<App />, document.getElementById('root'));

Summary

  • Passing and using Props: The parent component passes data to the child component, and the child component throughpropsreceives.
  • Default Props: UsedefaultPropsto set the component's default property values.
  • PropTypes validation: Useprop-typeslibrary to perform type checking on props.
  • Passing callback functions: The parent component can pass functions as props to child components to enable communication between components.
  • Destructuring props: Destructure props in function components to simplify code.

State and Props

The following example demonstrates how to use state and props together in an application. We can set state in the parent component and pass it to the child component via props on the child component. In the render function, we set name and site to get the data passed from the parent component.

React Example

class WebSite extends React.Component { constructor() { super(); this.state = { name: "Example", site: "https://www.example.com" } } render() { return ( <div> <Name name={this.state.name} /> <Link site={this.state.site} /> </div> ); } } class Name extends React.Component { render() { return ( <h1>{this.props.name}</h1> ); } } class Link extends React.Component { render() { return ( <a href={this.props.site}> {this.props.site} </a> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <WebSite /> );

Try it »

Props Validation

React.PropTypes, after React v15.5, has been moved to theprop-typeslibrary.

<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/prop-types/15.8.1/prop-types.min.js" type="application/javascript"></script>

Props validation usespropTypes, which ensures that our application components are used correctly. React.PropTypes provides many validators to validate whether the incoming data is valid. When invalid data is passed to props, the JavaScript console will throw a warning.

The following example creates a Mytitle component. The title prop is required and must be a string. Non-string types are automatically converted to strings:

React 16.4 Example

var title = "Example"; // var title = 123; class MyTitle extends React.Component { render() { return ( <h1>Hello, {this.props.title}</h1> ); } } MyTitle.propTypes = { title: PropTypes.string }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <MyTitle title={title} /> );

Try it »

React 15.4 Example

var title = "Example"; // var title = 123; var MyTitle = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired, }, render: function() { return <h1> {this.props.title} </h1>; } }); const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <MyTitle title={title} /> );

Try it »

Of course, we can introduce morePropTypesvalidators and how to use them. The following are some commonly usedPropTypesvalidator descriptions:

Basic data types

  • PropTypes.string: String
  • PropTypes.number: Number
  • PropTypes.boolean: Boolean
  • PropTypes.object: Object
  • PropTypes.array: Array
  • PropTypes.func: Function
  • PropTypes.symbol:Symbol

Special types

  • PropTypes.node: Anything that can be rendered: numbers, strings, elements, or arrays (including these types)
  • PropTypes.element: React element
  • PropTypes.instanceOf(Class): An instance of a class

Combined types

  • PropTypes.oneOf(['option1', 'option2']): Enum type, the value must be one of the provided options
  • PropTypes.oneOfType([PropTypes.string, PropTypes.number]): One of multiple types
  • PropTypes.arrayOf(PropTypes.number): An array of a certain type
  • PropTypes.objectOf(PropTypes.number): An object consisting of a certain type
  • PropTypes.shape({ key: PropTypes.string, value: PropTypes.number }): An object with a specific shape

Others

  • PropTypes.any: Any type
  • PropTypes.exact({ key: PropTypes.string }): An object with specific keys and no extra keys

The following are some example code snippets showing how to use differentPropTypesvalidators:

Example

import React from 'react';
import ReactDOM from 'react-dom/client';
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  static propTypes = {
    title: PropTypes.string.isRequired, // Must be a string and is required
    age: PropTypes.number,              // Optional number
    isAdmin: PropTypes.bool,            // Optional boolean
    user: PropTypes.shape({             // Must be an object with a specific shape
      name: PropTypes.string,
      email: PropTypes.string
    }),
    items: PropTypes.arrayOf(PropTypes.string), // Must be an array of strings
    callback: PropTypes.func,           // Optional function
    children: PropTypes.node,           // Optional renderable content
    options: PropTypes.oneOf(['option1', 'option2']), // Must be one of specific values
  };

  render() {
    return (
      <div>
        <h1>{this.props.title}</h1>
        {this.props.age && <p>Age: {this.props.age}</p>}
        {this.props.isAdmin && <p>Admin</p>}
        {this.props.user && (
          <div>
            <p>Name: {this.props.user.name}</p>
            <p>Email: {this.props.user.email}</p>
          </div>
        )}
        {this.props.items && (
          <ul>
            {this.props.items.map((item, index) => (
              <li key={index}>{item}</li>
            ))}
          </ul>
        )}
        {this.props.callback && (
          <button onClick={this.props.callback}>Click me</button>
        )}
        {this.props.children}
        {this.props.options && <p>Option: {this.props.options}</p>}
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <MyComponent
    title="Hello, World!"
    age={30}
    isAdmin={true}
    user={{ name: "John Doe", email: "[email protected]" }}
    items={['Item 1', 'Item 2', 'Item 3']}
    callback={() => alert('Button clicked!')}
    options="option1"
  >
    <p>This is a child element</p>
  </MyComponent>
);
Other Extensions