5

I am trying to change the state and URL onChange on a <Input type='select'>. (I am using reactstrap)

import React, {Component} from 'react'
import {
    Input,
} from 'reactstrap'

export default class NewPostComponent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            selected: '',
        }
    }

    handleChange(event) {
        this.setState({
            selected: event.target.value,
        })
    }

    render() {
        return (
            <Input type='select' onChange={(e) => handleChange(e)}>
                <option>option 1</option>
                <option>option 2</option>
                <option>option 3</option>
                <option>option 4</option>
            </Input>
        )
    }
}

I am changing the state but the problem comes at changing the URL. I have tried props.history.push but in handleChange as follows:

handleChange(event) {
    this.setState({
        selected: event.target.value,
    })
    this.props.history.push(`/${this.state.selected}/new/`)
}

This is the ERROR that I am getting

Uncaught TypeError: Cannot read property 'push' of undefined

console.log(this.props.history) is undefined.

I just need a way to change URL after setState occurs.

Sreekar Mouli
  • 1,313
  • 5
  • 25
  • 49

1 Answers1

6

The history prop is only passed to the components that are given to Route components.

{/* The Login component will get the history prop */}
<Route path="/login" component={Login} />

You could use withRouter if you want the route props in a component that is not directly used for a Route.

Since setState is asynchronous, you can push to the history in the callback to setState to make sure the state has changed before you change the url.

class NewPostComponent extends Component {
    state = {
        selected: ''
    }

    handleChange(event) {
        this.setState({
            selected: event.target.value,
        }, () => {
            this.props.history.push(`/${this.state.selected}/new/`)
        })
    }

    render() {
        return (
            <Input type='select' onChange={(e) => handleChange(e)}>
                <option>option 1</option>
                <option>option 2</option>
                <option>option 3</option>
                <option>option 4</option>
            </Input>
        )
    }
}

export default withRouter(NewPostComponent)
Tholle
  • 108,070
  • 19
  • 198
  • 189