Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
How to initiate state based on certain props

I'd like to initiate the state value of component A based on props it received. If it didn't receive that prop, the value should be a, but if it received a certain prop, the value should be b. the state will also be used as a default value of a select of this component A, the select option will change this state, and this state value will also be passed as a prop to a child component B. May I know what would be a good solution? Should I use ComponentDidUpdate, componentWillReceiveProps to reset State, ref or any other methods? Thanks!

class ComponentA extends Component {
    constructor(props) {
    super(props)
    this.state = {
    value: "a"
    }
  }
  
  componentWillReceiveProps(props) {
    const someProp = props[someKey];
    let someVal = someFunc(someProp);
    if (someProp) {
        this.setState({value:someVal})
    }
  }
}
...
handleChange = (val) => {
    this.setState({value:val})
}
......
<select 
  options ={options}
  value = {this.state.value}
  onChange = {this.handleChange}
/>
<Input
  selectVal = {this.state.value}
/>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Keep it like this , You can also use setState in condition while defining the state above


const [state, setState] = useState ('a');
if(prop.value)
   setState ('a');
else
   setState ('b');

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!