Redirecting from the search form to the reaction results page

I am currently developing my first response application, and I am having difficulty moving from the Search component to the Results component using response-router-dom.

The search component accepts entries from the user, executes a receive request using axios, and updates the status of its results.

import axios from 'axios';
import React, {Component} from 'react';
import {Button} from 'react-bootstrap';
import Results from './Results';

class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      term: '',
    };

    this.submit = this.submit.bind(this);
    this.changeTerm = this.changeTerm.bind(this);
  }

  changeTerm(event) {
    this.setState({term: event.target.value});
  }

  submit(event) {
    let url = 'http://api.example.com/results?q=' + encodeURI(this.state.term) + '&json=1';
    axios.get(url)
      .then(response => {
        let data = {
          results: response.data,
        };
        this.setState(data);
      })
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div>
        <form onSubmit={this.submit}>
          <input onChange={this.changeTerm}/>
          <Button type="submit" bsStyle="primary">Find</Button>
        </form>
        <Results data={this.state.results}/>
      </div>
    );
  }
}

export default Search;

Currently, the results are displayed directly below the search component, but I would like to redirect the results to a new page with a different URL. Both pages must be different because they have completely different structures and styles and must point to different URLs.

"" "" ? , .

+4
1

Redirect? ( ), . , - , .

class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      term: '',
    };

    this.submit = this.submit.bind(this);
    this.changeTerm = this.changeTerm.bind(this);
  }

  changeTerm(event) {
    this.setState({term: event.target.value});
  }

  submit(event) {
    let url = 'http://api.example.com/results?q=' + encodeURI(this.state.term) + '&json=1';
    axios.get(url)
      .then(response => {
        let data = {
          results: response.data,
        };
        this.setState(data);
      })
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div>
        <form onSubmit={this.submit}>
          <input onChange={this.changeTerm}/>
          <Button type="submit" bsStyle="primary">Find</Button>
        </form>
        {this.state.results.length > 0 &&
          <Redirect to={{
            pathname: '/results',
            state: { results: this.state.results }
          }}/>
        }
      </div>
    );
  }
}

export default Search;
+5

Source: https://habr.com/ru/post/1673029/


All Articles