React - Props

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

props is the only object argument passed to a component

Props is similar to State, but it is public and not fully controlled by the component.

Advertising

3 - Syntax

in React - JSX

index.jsx
<MyComponent name={javascriptVariable} color="Blue"/>

will create two props

  • props.name
  • and props.color

4 - Requirements

Props:

  • must be named from the component's own point of view rather than the context in which it is being used.
  • are read-only. A component must never modify its own props. It must modify it via this.setState() All React components must act like pure functions with respect to their props. See React - State

5 - Management

5.1 - Default value

Default values are defined by assigning to the special defaultProps property to the component.

index.jsx
class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
  • Specifies the default value for the name prop:
index.jsx
Greeting.defaultProps = {
  name: 'Stranger (Default)'
};
  • And render
index.jsx
ReactDOM.render(
  <Greeting />,
  document.getElementById('root')
);
index.html
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>

Advertising

5.2 - Type checking

Type checking with prop-types

PropTypes exports a range of validators that can be used to make sure the data you receive is valid. In this example, we're using PropTypes.string. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, propTypes is only checked in development mode.

Example: the name property must be a string:

import PropTypes from 'prop-types';
 
class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
 
Greeting.propTypes = {
  name: PropTypes.string
};

List

  • PropTypes.string
  • PropTypes.bool,
  • PropTypes.func,
  • elementType,
  • PropTypes.oneOf(['button', 'reset', 'submit']),
  • PropTypes.func.isRequired,
  • PropTypes.object.isRequired
  • PropTypes.arrayOf
PropTypes.arrayOf(
        PropTypes.shape({
            id: PropTypes.string.isRequired,
            title: PropTypes.string.isRequired,
        })
    ).isRequired,
Advertising

5.3 - Get

With the chrome plugin

6 - Documentation / Reference

web/javascript/react/props.txt · Last modified: 2019/06/21 14:36 by gerardnico