0

I have a react applictation with react-router for navagation. I try to create form that is update some data. After submit the data are send to server though ajax request and in case of ajex response is "Ok" than the user has to be redirected to another page (in my case url in react-router is /carwash) and information about succesfull update has to be shown in the distination page.

I tried to do this by 3 differect ways:

1) this.props.history.push('/carwash') The result was exception:Uncaught TypeError: Cannot read property 'push' of undefined

2) browserHistory.push("/carwash"), the result is the list in browser was changed but there isn't any redirection

3) redirection on absolute url w/o react: window.location.replace("/owner.html#/carwash"), the result was succesfull but I don't undestand how to inform destitaion page the data was update succesfull.

Can you explain me what is the best way for redirection in react and how to use it? And what is not less important how to infom page where the user will be redirected that the data was update succefull ?

My code has the following view:

import React from 'react';
import {Router} from 'react-router';
import Loading from './form/loading.jsx';

export default class EditCarWashForm extends React.Component{

static contextTypes = {
    router: React.PropTypes.object.isRequired
};

constructor(props) {
    super(props);
    this.state = {
        name        :  {value : constants.EMPTY_FIELD, isValid : false},
        address     :  {value : constants.EMPTY_FIELD, isValid : true},
        isCarWashDownload : true
    };
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(e) {
    e.preventDefault();
    let carWashData = {some logic}

    $.ajax({
        url: '/carwash/',
        type: 'POST',
        async: true,
        cache: false,
        contentType: 'application/json',
        data: JSON.stringify(carWashData),
        dataType: 'json',
        success: function(data) {
            if (data.message == 'Ok'){
               // browserHistory.push("/owner.html#/carwash")
                this.props.history.push('/carwash');
               // window.location.replace("/owner.html#/carwash");
        }
        }.bind(this),
    })
};


render(){
    let data = <Loading/>

    if (this.state.isCarWashDownload) {
        data =
            <form onSubmit={this.handleSubmit} id="addCarWashForm">
                <FormInputField
                    title="Name*:"
                    placeholder="Name"
                    name="name"
                    required={true}
                    maxLength={50}
                    defaultValue={this.state.name.value}
                />

                <FormInputField
                    title="Adress:"
                    placeholder="Adress"
                    name="address"
                    maxLength={200}
                />


                <div className="form-group">
                    <div className="col-sm-offset-2 col-sm-10">
                        <button type="submit">Update</button>
                    </div>
                </div>

            </form>
    }

    return (
        <div>
            {data}
        </div>
    )

}

}

Bizon4ik
  • 2,604
  • 4
  • 20
  • 46
  • You're confusing a couple of concepts. You've created a Single Page App (SPA) and then you are using the word `redirect` which generally doesn't apply to SPA's. Are you literally wanting the browser to refresh or do you simply need `react` to render a different component/page? They are literally 2 different things. – Gregg Oct 10 '16 at 21:22
  • @Gregg sorry for confuse but redirect it's official name of react, react router even has compinent - sets up a redirect to another route in your application to maintain old URLs [link](https://github.com/ReactTraining/react-router/blob/master/docs/API.md#redirect) – Bizon4ik Oct 10 '16 at 21:35

2 Answers2

2

Try importing browserHistory like:

// Somewhere like a Redux middleware or Flux action:
import { browserHistory } from 'react-router'

// Go to /some/path.
browserHistory.push('/some/path')

check here

M.Sharma
  • 224
  • 1
  • 7
  • I did but it not make redirection. I added into ajax success the following code: `browserHistory.push('/carwash')` . In console i see that ajax send post request and then there is not any action only url in browser was changed from `http://localhost:8080/owner.html#/carwashAdd/3?_k=76k2wy` to `http://localhost:8080/carwash` NB: I don't use redux or flux – Bizon4ik Oct 10 '16 at 19:18
  • using window.location is not a recommended way and should be avoided. there is a similiar question, worth checking http://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router – M.Sharma Oct 10 '16 at 19:32
2

This code is working for redirection:

// Somewhere like a Redux middleware or Flux action:
import { browserHistory } from 'react-router'

// Go to /some/path.
browserHistory.push('/some/path')

My fault was in main component that is responsible for rendering <Router>. I had the following code that mention history not as browserHistory but as hashHistory

ReactDOM.render(
<Router history={hashHistory}>
    <Route path="/" component={MyHeader}>
        <IndexRoute component={Main}/>
        <Route path="carwash" component={CarWashPage} />
        <Route path="carwashAdd" component={AddCarWashPage} />
        <Route path="carwashAdd/:carWashId" component={EditCarWashPage} />

    </Route>
</Router>,
destination
);

In view of that the redirection is working if make the following changes (in my case):

hashHistory.push('/some/path');
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Bizon4ik
  • 2,604
  • 4
  • 20
  • 46
  • That's not really a redirect. But glad you got it working. – Gregg Oct 10 '16 at 21:24
  • @Gregg thank you but it solve one part of my issues. I still don't know how to show information in destination page after such kind of redirection. I want to show text like "data was updated succesfully" – Bizon4ik Oct 10 '16 at 21:31