Update This.state Conditionally When Rendering Component In React?
I have a time picker that I want to set the value to this.state.start. However the value of this.state.start could be equal to this.props.normal or this.props.spec depending on whe
Solution 1:
You could have a function that sets this.start.state
like so:
class NormalHours extends React.Component {
constructor(props) {
super(props)
this.state = {
start: null,
}
this.setStart();
}
setStart = () => {
if(this.props.specStart == this.props.normStart || this.props.specStart == null)
{
//If special hours are null or equal to normal start use normal hours
this.setState({
start: this.props.normStart;
});
}
else
{
//Else the hours are different so use special hours
this.setState({
start: this.props.specStart;
});
}
}
render() {
return(
<div>
//Using Material UI; this is rendered as a textbox
<TimePicker
name="StartTime"
onChange={(e, date) => {
this.props.onSetStartTime(Utils.convertDateToTimeString(date))
}}
value={this.state.start}
/>
</div>
)
}
}
I'm not too clued up on whether calling methods in the constructor is considered bad practice or whether or not
this.state = {
start: null
}
is even required when you're modifying state immediately after.
Post a Comment for "Update This.state Conditionally When Rendering Component In React?"