Peter Tao
Peter Tao

Reputation: 1708

Radio button does not update UI in NavItem

Bugged code (also below): https://codesandbox.io/s/4xklz52xkx

The radio button should become checked after clicking on it, but does not. This only occurs in a NavItem. Removing the NavItem div makes the radio buttons work again: https://codesandbox.io/s/5x60q3440l

Could be related to this react bootstrap issue, which was never resolved. The SO post for that issue is here. I have tested the work around in the answer, with no luck either.

import React from "react";
import { render } from "react-dom";
import { Nav, NavItem, Radio } from "react-bootstrap";
import { BrowserRouter as Router } from "react-router-dom";

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: "one"
    };
  }

  handleChange = e => {
    this.setState({ selected: e.target.value });
    console.log(this.state);
  };

  render() {
    return (
      <div>
        <Nav bsStyle="tabs">
          <NavItem>
            <Radio
              name="radioGroup"
              checked={this.state.selected === "one"}
              value="one"
              onChange={this.handleChange}
            >
              one
            </Radio>
            <Radio
              name="radioGroup"
              checked={this.state.selected === "two"}
              value="two"
              onChange={this.handleChange}
            >
              two
            </Radio>
          </NavItem>
        </Nav>
      </div>
    );
  }
}

const App = () => (
  <Router>
    <Menu />
  </Router>
);

render(<App />, document.getElementById("root"));

Upvotes: 0

Views: 213

Answers (2)

yaswanth
yaswanth

Reputation: 2477

For some reason, adding a non empty href to NavItem gets it to work. If you change the NavItem to

<NavItem href = '#!'>

it works fine. As long as you leave href empty or use # for href, it doesn't work. I named the href #! assuming you won't name any of your html elements with ! !!

I presume this code snippet in react bootstrap is the issue. But I'm not entirely sure. I'll find the root cause and update the answer.

Upvotes: 1

ayeteo
ayeteo

Reputation: 254

Try using e.preventDefault() in your handler. Looks like its defaulting to it's original state.

Upvotes: 0

Related Questions