'React Radio input selection persists on re-render
I am rendering a component including radio inputs. When a radio input selection is made, and the change is updated in state (Zustand if it matters), the component re-renders.
However, the radio selection is persisted on the re-render. Why is this not being cleared on re-render? And/or how to I reset this?
Attached is a simplified case.
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0,
}
}
update = () => {
this.setState({
count: 4
})
}
render() {
return (
<div>
<div>
<input id="one" type="radio" name="test"></input>
<label htmlFor="one">one</label>
</div>
<div>
<input id="two" type="radio" name="test"></input>
<label htmlFor="two">two</label>
</div>
<button onClick={this.update}>Update state from 0 to 4</button>
<h2>Count in state: {this.state.count}</h2>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
============================================================
Update.
The issue was that I was outputting the radio buttons using map
, and assigning the index key attribute.
const radioInputs = allItems.map((item, index) => {
return (
<div key={index}>
<input type="radio" ....../>
<label .....>{item.name}</label>
</div>
)
}
Because the same index was used on subsequent re-rendering, and React uses the key as sort of ID (docs), the next radio input with the same key was selected as the previous selection.
I just needed to use a "globally" unique key, as opposed to the index from map
.
Solution 1:[1]
its actually Reacts beauty; in React we have virtual dom: abstraction layer on top of real dom. It consists of your React application's elements.
State changes in your application will be applied to the VDOM first. If the new state of the VDOM requires a UI change, the ReactDOM library will efficiently do this by trying to update only what needs to be updated.
For example, if only the attribute of an element changes, React will only update the attribute of the HTML element by calling document.setAttribute
When the VDOM gets updated, React compares it to to a previous snapshot of the VDOM and then only updates what has changed in the real DOM. If nothing changed, the real DOM wouldn't be updated at all. This process of comparing the old VDOM with the new one is called diffing.
thats why your radio buttons dont change when another state changes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ahmetkilinc |