Ariel Flores
Ariel Flores

Reputation: 21

Dropdown menu with onClick

I'm trying to create a dropdown menu with 3 options. Once an option is selected, it triggers an change in a state. I tried a few different ways but they don't work.

This is the first attempt:

<div className='dropDownDiv'>
  <select>  
    <button onClick={()=> setResultsPerPage(6)}>6 Results</button>
    <button onClick={()=> setResultsPerPage(9)}>9 Results</button>
    <button onClick={()=> setResultsPerPage(15)}>Max sites</button>
  </select>
</div>

Then I tried this:

<div className='dropDownDiv'>
  <select>  
    <option onClick={()=> setResultsPerPage(6)}>6 Results</option>
    <option onClick={()=> setResultsPerPage(9)}>9 Results</option>
    <option onClick={()=> setResultsPerPage(15)}>Max sites</option>
  </select>
</div>

The second attempt shows the options in the dropdown but still doesn't trigger the onClick. Any idea what I'm doing wrong?

Thanks!

Upvotes: 0

Views: 10772

Answers (1)

romellem
romellem

Reputation: 6491

For select tags, you want to add a change event listener on the parent select element rather than the individual option elements.

The option elements should have a value, which is then read in the onChange handler from the event's target.

function Form() {
    const [resultsPerPage, setResultsPerPage] = React.useState(6);

    return (
        <div>
            <select value={resultsPerPage} onChange={(event) => setResultsPerPage(event.target.value)}>
                <option value={6}>6 Results</option>
                <option value={9}>9 Results</option>
                <option value={15}>Max sites</option>
            </select>
            <p>Results per page: {resultsPerPage}</p>
        </div>
    );
}

ReactDOM.render(<Form />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script>

<div id="app"></div>

Upvotes: 2

Related Questions