Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set defaultProp value based on value of other prop?

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?

like image 996
mohsinulhaq Avatar asked Jul 30 '18 06:07

mohsinulhaq


People also ask

How do we set a React component to use a default value for some prop?

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.

Can we assign value to props?

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 .

Where would you specify the default values for a component's props?

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.

Can we have default values for props?

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.


1 Answers

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,
};
like image 150
TVG Avatar answered Oct 23 '22 23:10

TVG