简体   繁体   中英

How can I change form fields based on dropdown selection with reactJS

In my dropdown I have two options, Yes or No I want one component to render when user select Yes and other to another component to render if user selects No. Also I want when page refresh, no options should be shown on page

Check Image

How can I achieve my goal? I am sharing my code below

Here is the dropdown fields, 
const CustomTimings=[
  {label:'Yes', value: 1},
  {label:'No', value: 2}
]

const DateAndTime = () => (
      <div>
        {CustomTimings === 'Yes'
        ? <CustomeTimeYes />
        : <CustomeTimeNo />
    }
return
<div className="input-field">
            <div class="row">
              <div class="col-4">
              <label htmlFor="customerype">Customer Type</label><br />
              <Select options={CustomerType} onChange={this.handleChangeCT} value={this.state.CustomerType} />
              </div>
              <div class="col-4">
              <label htmlFor="learning">Do you have custom timings</label><br/>
              <Select options={CustomTimings} onChange={this.handleChangeCTime} value={this.state.CustomTimings} />
              </div>
            </div>
          </div><br />
          <div>
          {DateAndTime()}
          <br />
          </div>

Can somebody explain what I am doing wrong here, either it is showing both components or any one and not changing on refresh

You can work with conditional rendering where you check for a specific condition before render your component.

render() {
const { value } = this.state;

return (
   <div>
       {value === 'dropdown' && <Component1>...</Component1>}
       {value === 'text' && <Component2></Component2>}
       {value === 'checkboxes' && <Component3></Component3>}
       ...
   </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM