1

I am using React Router and trying to navigate to another page on a radio button selection of "No". Please let me know if this is achievable.

karthik
  • 81
  • 1
  • 1
  • 8

1 Answers1

1

You can change route programmatically with history.push or history.replace - full documentation https://reacttraining.com/react-router/web/api/history. If you want to navigate to another page, you can do that with window.location.href - see question: What's the difference between window.location= and window.location.replace()? - since Redirect (https://reacttraining.com/react-router/web/api/Redirect) cannot help in your case. Not sure which navigation you need (another route or page), but you can handle it inside of onChange event handler on your radio button.

import React, { Component } from "react";

export default class RadioButtons extends Component {
  state = { selectedOption: "" };

  handleOptionChange = e => {
    if (e.target.checked && e.target.value === "no") { // if value of "No" option is selected
      this.props.history.push("newRoute"); // navigate to another route
      //window.location.href = "https://www.google.com"; - if you want to navigate to another page
    }
    this.setState({ selectedOption: e.target.value });
  };

  render() {
    const { selectedOption } = this.state;
    const { history } = this.props;

    return (
      <div>
        <div className="radio">
          <label>
            <input
              type="radio"
              checked={selectedOption === "yes"}
              onChange={this.handleOptionChange}
            />
            Yes
          </label>
        </div>
        <div className="radio">
          <label>
            <input
              type="radio"
              value="no"
              checked={selectedOption === "no"}
              onChange={this.handleOptionChange}
            />
            No
          </label>
        </div>
      </div>
    );
  }
}

Or you can just put different onChange handler for radio button "No", to avoid checking is "Radio" button triggered or not.

<div className="radio">
  <label>
    <input type="radio" value="no"
       checked={selectedOption === "no"}
       onChange={e => this.props.history.push('newRoute') || window.location.href= "https://www.google.com" }
     />
     No
   </label>
 </div>
</div>

You can see full code here: https://codesandbox.io/s/m3omno7olx Hope this helps!

Vikky
  • 750
  • 8
  • 16