I have a component that has one required property and one optional property. An optional property acts as an override mechanism, which, if not present, defaults to the value obtained from the required property. It is configured as follows:
function fruitColour(fruit) {
switch (fruit) {
case 'banana':
return 'yellow';
}
}
const Fruit = (props) => {
const { type } = props;
let { colour } = props;
colour = colour || fruitColour(type);
return <p>A yummy {colour} {type}!</p>
}
This allows me to have a ripe ripe banana:
<Fruit type='banana' />
Or a younger, unripe banana:
<Fruit type='banana' colour='green' />
The project I'm working on establishes that if the value is propnot read as a constant, it should be set to the default value of defaultProps. I am currently doing this:
Fruit.defaultProps = {
colour: ''
}
But this is stupid because my component logic already handles the default state.
I am stuck in this template or you can read the property typein defaultPropsto do something like this:
Fruit.defaultProps = {
colour: (props) => fruitColour(props.type)
}
... colour , ?