skip to Main Content

Im new to react, Im acheiving to search the text,which will post to the api, and the results will be displayed as options in box,for which im using twitter bootstrap just the className’s to match with REACT.I want to make the make the option's value to be bind to the input text box above, if i select the option. How to achieve this using useRef and at the same time ,the select box should close if the option is selected.The HandleCHange for the input box triggers the api call for every keystrole

Below is the code for the select box.

 <input
        className='form-control'
        placeholder='Search Drug...'
        onChange={handleChange}
      />
<select class='custom-select' size={drugList.drugs?.length> 0 ? '10' : ''} onChange={handleSelectChange}>
        
        {drugList.drugs?.length > 0 &&
          drugList.drugs.map((each,index) => {
            return (
              <option key={index} value={`${each.drug}`}>
                {each.drug}
              </option>
            )
          })}
     
      </select>

Here i want the selected value to be bind to the input box.It will be great if you give the sample code or snippet.

enter image description here
Please refer the image above.Thanks in Advance!

2

Answers


  1. I think you can do this like this.

    handleSelectChange = (event) =>{
     this.setState({selectvalue:event.target.value});
    }
    handleChange= (event) =>{
      this.setState({selectvalue:event.target.value});
       ---- and your code here---
    } 
    
    <input
        className='form-control'
        placeholder='Search Drug...'
        onChange={this.handleChange}
        value={this.state.selectvalue}
    />
    <select class='custom-select' size={drugList.drugs?.length> 0 ? '10' : ''} onChange={this.handleSelectChange}>            
            {drugList.drugs?.length > 0 &&
              drugList.drugs.map((each,index) => {
                return (
                  <option key={index} value={`${each.drug}`}>
                    {each.drug}
                  </option>
                )
              })}             
    </select>
    
    Login or Signup to reply.
  2. I want to make the make the option’s value to be bind to the input text box above
    —> use component state to store the selected value from the options dropdown
    at the same time ,the select box should close if the option is selected.
    —-> hide/display select options based on input box focus by toggling component state.

    created a sandbox for your app, please check

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search