StarBoy
StarBoy

Reputation: 154

React router "context.router.transitionTo is not a function"

I am using "react-router": "^4.2.0", "react-router-dom": "^4.2.2", All I am trying to do is when I submit form in one page it has to direct to the another defined page(component). Here is my code

FormValue.js

import React from "react";

class FormValues extends React.Component{
  gotoStore(e){
    e.preventDefault();
    let id = this.storeInput.value;
    this.context.router.transitionTo(`${id}`);
 }

render(){
    return (
            <form onSubmit={(e) => this.gotoStore(e)}>
                <input type="text" placeholder="enter your name" 
                 ref={(input) => {this.storeInput = input}}/>
                <button type="submit">Submit</button>
            </form>
    )
}
}

FormValues.contextTypes = {
 router: React.PropTypes.object
}

 export default FormValues;

index.js

  import React from "react";
  import { render } from 'react-dom';
  import {BrowserRouter, Route} from "react-router-dom";
  import ReactDom from "react-dom";
  import App from './App';
  import FormValues from './FormValues';

  const Root = () => {
   return (
    <BrowserRouter>
        <div>
            <Route path="/" exact component={FormValues}/>
            <Route path="/:id" exact component={App}/>

        </div>
    </BrowserRouter>
   )
  }

  ReactDom.render(<Root/>, document.getElementById('root'));

and I am getting error as enter image description here

any help would be appreciated

Upvotes: 0

Views: 1593

Answers (3)

kach 234
kach 234

Reputation: 1

import { PropTypes } from "prop-types";

  goToStore(event) {

     event.preventDefault();

     const storeId = this.storeInput.value;

     this.context.router.history.push(`/store/${storeId}`);

  };

  StorePicker.contextTypes = {

    router: function contextType(){

     return PropTypes.object;

    }
  }

Upvotes: 0

fish
fish

Reputation: 39

Since we can already access history under props, we don't even need to import PropTypes anymore. If you notice, when calling this.props.history we're not even touching the router context we declare later with PropTypes. Simply having the below code as is works:

goToStore(e) {
 e.preventDefault();
 const storeId = this.storeInput.value;
 this.props.history.push(`store/${storeId}`);
}

Upvotes: 0

My solution is:

import { PropTypes } from 'prop-types';

goToStore(e) {
 e.preventDefault();
 const storeId = this.storeInput.value;
 this.props.history.push(`store/${storeId}`);
}

StorePicker.contextTypes = {
  router: PropTypes.object
}

Upvotes: 2

Related Questions