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
- props.name
- and props.color
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
Management
Default value
Default values are defined by assigning to the special defaultProps property to the component.
- A class greeting component with one prop: name
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
- Specifies the default value for the name prop:
Greeting.defaultProps = {
name: 'Stranger (Default)'
};
- And render
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
Get
With the 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}}/>
}