0

When I click Link, I want to show a modal to ask user, if they really want to make the change. If they click "YES", I want continue to redirect to other page.

Here is my code:

import { Modal } from 'antd';
import { Link } from 'react-router-dom';
import React from 'react';
const confirm = Modal.confirm;


class Menu extends CLComponent {
  constructor (props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.showModal = this.showModal.bind(this);
    this.confirmChange = this.confirmChange.bind(this);
  }


  linkClick (e) {
    let hashValue = e.target.getAttribute("href");
    e.preventDefault();
    e.stopPropagation();
  }

  showModal (url) {
    const that = this;
    confirm({
      title: 'Sure leave?',
      content: "Are you sure to leave this page?",
      onOk() {
        that.confirmChange(url);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  confirmChange () {
    location.hash = e;
  }

  render() {
    return (
      <div>
        <Link onClick={ this.linkClick } to={"/test"}>test</Link>
      </div>
    );
  }
}

Altrough I make it work, but I felt it is so bad. Is there any way to change my code?

jhonyoung
  • 1
  • 2

2 Answers2

0

You can use push from react-router-redux to push the location on confirm.

Here is an example:

import {connect} from "react-redux";
import {push} from "react-router-redux";
...
showModal (url) {
  const that = this;
  confirm({
    title: 'Sure leave?',
    content: "Are you sure to leave this page?",
    onOk() {
      this.props.dispatch(push(url));
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}
...
Yash Thakur
  • 1,172
  • 7
  • 14
0

Convert link to button and use react router history.push(path) to go to another location

import { Modal } from 'antd';
import { Link, withRouter } from 'react-router-dom'; //use withRouter HOC in case this is not a direct child of Route or in case u do not have access to history prop
import React from 'react';
const confirm = Modal.confirm;

class Menu extends CLComponent {
  constructor (props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.showModal = this.showModal.bind(this);
    this.confirmChange = this.confirmChange.bind(this);
  }


  linkClick () {
  const that = this;
   confirm({
      title: 'Sure leave?',
      content: "Are you sure to leave this page?",
      onOk() {
        that.props.history.push('/test');
      },
      onCancel() {
        console.log('Cancel');
      },
    });


  }
  render() {
    return (
      <div>
        <button onClick={ this.linkClick }>test</button>
      </div>
    );
  }
}
export default withRouter(CLComponent) 
Gautam Naik
  • 8,990
  • 3
  • 27
  • 42