I have a component where the default value of one prop depends on the value of another prop (default or user provided). We can't do the following because we don't have access to this
:
static defaultProps = {
delay: this.props.trigger === 'hover' ? 100 : 0,
trigger: 'hover'
};
How can I best do this?
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
You would change the prop in the parent component, as that is what holds the value of the prop itself. This would force a re-render of any child components that use the specific prop being changed. If you want to intercept the props as they're sent, you can use the lifecycle method componentWillReceiveProps .
You can define default values for your props by assigning to the special defaultProps property: class Greeting extends React. Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } // Specifies the default values for props: Greeting.
Default props can be used to define any props that you want to be set for a component, whether or not a value is actually passed in from the parent component. When using default props, you can still override the values specified in the default props object when you pass in values from the parent component.
Using a function component you can do it like this:
function MyComponent({
trigger,
delay: trigger === 'hover' ? 100 : 0,
}) {
return <div>...</div>
}
MyComponent.propTypes = {
trigger: PropTypes.string.isRequired,
delay: PropTypes.number.isRequired,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With