3

How to redirect in react router in self page. e.g I have a component ProfileUpdate it updates name & stores to backend. After successful update I want to redirect to same page but it's not working. Here is a sample code.

class ProfileUpdate extends Component {
    constructor() {
        super();

        this.state = {
            name: ''
        };
  }

  onSubmit(e) {
    e.preventDefault();
    this.props.history.replace('/');    
  }

  onChange(e) {
    const name = e.target.value;
    this.setState(() => ({
      name
    }))
  }

    render() {
        return (
            <form onSubmit={this.onSubmit}>
                <div>
                    <h4>Display Name:</h4>
                    <div>
                        <input name='displayName' placeholder='Display name' type='text' value={this.state.name} onChange={this.onChange} />
                    </div>
                </div>
                <div>
                    <button type='submit'>Update</button>
                </div>
            </form>
        );
    }
}

Expected behaviour if I update name then click submit it will replace the route/redirect & name input should be empty.

But when I choose a different path to replace it works. e.g this.props.history.replace('/users') it works. But here this.props.history.replace('/'); it doesn't work.

ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58
  • window.location.reload() – Jayakumar Thangavel Nov 13 '19 at 07:55
  • https://stackoverflow.com/questions/31539349/how-to-emulate-window-location-with-react-router-and-es6-classes/31553732#31553732 – Jayakumar Thangavel Nov 13 '19 at 07:55
  • @JayakumarThangavel thanks for your comment but if I use `window.location.reload()` it will be reload not redirect & if I use `window.location.href` won't in both cases it will be full page refresh, As we are using react router I guess this should be my last choice. However thanks once again. – ARIF MAHMUD RANA Nov 13 '19 at 14:08

0 Answers0