0

I'm trying to navigate in my react app after some functionality occurs. Normally I would use window.location to do this, however, I was told to avoid page refreshes in a Single Page App such as mine. I'm struggling to get it to navigate away.

I am using react-router-dom and react-dnd. Because of react-dnd the history is not getting passed down the way it normally would.

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { DragSource } from 'react-dnd'
import ItemTypes from '../ItemTypes'
import { BrowserRouter } from 'react-router-dom'
const style = {
    fontSize: '126px', 
    'cursor': 'move',   
}

const boxSource = {
    beginDrag(props) {
        return {
            name: props.name,
        }
    },

    endDrag(props, monitor) {
        // const item = monitor.getItem()
        const dropResult = monitor.getDropResult()

        if (dropResult) {
            // window.location.href = 'http://localhost/book/'
            // what do i put here to navigate away
        }
    },
}


class Key extends Component {
    static propTypes = {
        connectDragSource: PropTypes.func.isRequired,
        isDragging: PropTypes.bool.isRequired,
        name: PropTypes.string.isRequired,
    }

    render() {
        const { isDragging, connectDragSource } = this.props
        const { name } = this.props
        const opacity = isDragging ? 0.4 : 1

        return connectDragSource(<div style={{ ...style, opacity }}>{name}</div>)
    }
}

// @DragSource(ItemTypes.BOX, boxSource, (connect, monitor) => ({
//  connectDragSource: connect.dragSource(),
//  isDragging: monitor.isDragging(),
// }))

export default DragSource(ItemTypes.BOX, boxSource, (connect , monitor) => {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging(),
    }
})(Key)

I've tried to use browserHistory with react-router but BrowserRouter does not take history as a prop by default.

If I have to use window.location just let me know.

Kelrynn
  • 588
  • 5
  • 8

1 Answers1

0

Try using push:

if (dropResult) {
  history.push('/book')
}

See this for more detail.

SeanPlusPlus
  • 8,663
  • 18
  • 59
  • 84
  • You're right, normally that would work. However because I am also using [react-dnd](https://react-dnd.github.io/react-dnd/) the history isn't getting passed down in the same manner. – Kelrynn Dec 04 '17 at 19:13
  • Can you try passing history as a param here: endDrag(props, monitor) – SeanPlusPlus Dec 04 '17 at 19:20
  • 1
    [This answer](https://stackoverflow.com/a/42121109/7491889) seems to address this same problem. Personally, I'd recommend the withRouter HOC if possible. – T Porter Dec 04 '17 at 19:26