Table of Contents

React - Props

About

props is the only object argument passed from a component to another component.

Syntax

in React - JSX

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

will create two props

Requirements

Props:

Management

Default value

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

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

Type checking

built-in Type checking in React is known as prop-types

Change children type

See How to define the React children type in Typescript?

Get

With the chrome plugin

React Props Chrome Plugin

How to pass the keys of an object as props?

You use the spread operator to destructure the object.

Example:

let props = { "x": 10, "y": 20 };
<Component {...props}/>

How to add props and pass parent props to a child?

Example with the spread operator to merge properties.

function Parent(parentProps){
  return <Child  {...{extra: 'value', ...parentProps}}/>
}

Example how to add a class Name

function Parent(parentProps){
  return <Child  {...{...parentProps, className: 'value '+parentProps.className}}/>
}

Documentation / Reference