简体   繁体   中英

Is there any way to trigger a react-select dropdown with jquery from browser?

<select id="selelct-dropdown">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

For normal select like this I can change the selected value by using

$('#select-dropdown').val(1)

But when I using react-select there is no select tag nor option tag shown in browser Is there any way to change the react-select dropdown value by jquery?

You don't really need to use jquery, instead maintain the state for field and then set state with the value. As per documentation of react-select:

        import React, { Component, useState } from 'react'
        import Select from 'react-select'
        
        const options = [
          { value: 'chocolate', label: 'Chocolate' },
          { value: 'strawberry', label: 'Strawberry' },
          { value: 'vanilla', label: 'Vanilla' }
        ]
        
        const MyComponent = () => {
          const [value, setValue] = useState('')
          return (
          <Select options={options} value={value} onChange={(e) => 
            setValue(e.target.value)} />
           )
        }
export default MyComponent;

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