I’m trying to use React useState to change the value of dropdown value, but it looks like it refreshes the page after onClick has been called. When I click for example on option B, it changes selectedValue state to B, then it re-render the page and reset it to default value. My question is why it re-renders the page? And how can change the dropdown value?
import React, {useState} from 'react';
function InputDropdown(props) {
const [selectedValue, setSelectedValue] = useState("");
return (
<div className="input-group">
<input type="text" className="form-control" />
<div className="input-group-append">
<button type="button" className="btn btn-outline-secondary">{selectedValue}</button>
<button type="button" className="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown">
<span className="sr-only">Toggle Dropdown</span>
</button>
<div className="dropdown-menu">
<a class="dropdown-item" href="#" onClick={() =>setSelectedValue("A")}>A</a>
<a class="dropdown-item" href="#" onClick={() =>setSelectedValue("B")}>B</a>
<a class="dropdown-item" href="#" onClick={() =>setSelectedValue("C")}>C</a>
</div>
</div>
</div>
)
}
In React, if any state value changed, the component will be re-rendered. That’s why your new state value will be refreshed on the page.
In your example,
selectedValue
is empty at the beginning.when you selected a value, you called
setSelectedValue()
(beware your option B value is C may be a bug)it changed the
selectedValue
local state’s value, the component re-rendreed. That’s why after re-rendered, on your button the value changed to your selected value.