1

When onClick event is triggered, I want to redirect to a new component (props passed to it) with a new url.

My App.js

import React from "react";
import Main from "./Components/Main/Main";
import "bootstrap/dist/css/bootstrap.min.css";
import styles from "./App.module.css";
import { BrowserRouter as Router, Route} from "react-router-dom";
import SearchBar from "./Components/SearchBar/SearchBar";
import AnimeInfo from "./Components/AnimeInfo/AnimeInfo";
import Cards from "./Components/Cards/Cards"

const App = () => {
  
  return (
    <Router>
    <div className={styles.container}>
      <SearchBar />
        <Route path="/" exact component={Main} />
        <Route path="/anime/info" component={AnimeInfo} />
        <Route path="/anime/cards" component={Cards} />
      </div>
    </Router>
  );
};

export default App;

In the following component, I am passing props to a component but I want to redirect to the url too, but doing so, the props passed that component are lost and I just get redirected

import React, { useEffect, useState } from "react";
import { apiDataTop, apiDataUpcoming, apiDataDay } from "../../api";
import styles from "./TopAnime.module.css";
import AnimeInfo from "../AnimeInfo/AnimeInfo";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
} from "react-router-dom";

const TopAnime = () => {
  const [animeData, setAnimeData] = useState([]);
  const [animeDataHype, setAnimeDataHype] = useState([]);
  const [animeDataDay, setAnimeDataDay] = useState([]);
  const [image_url, setImageUrl] = useState("");
  useEffect(() => {
    callApi();
  }, []);

  const callApi = async () => {
    const results = await apiDataTop();
    const hypeResults = await apiDataUpcoming();
    const dayResults = await apiDataDay();
    setAnimeData(results);
    setAnimeDataHype(hypeResults);
    setAnimeDataDay(dayResults);
  };

  console.log(animeDataDay);

  return (
    <div>
      <h1>Recent Release</h1>
      <div className={styles.container}>
        <br />
        {animeDataDay === []
          ? null
          : animeDataDay.map((anime) => {
              return (
                <a
                  href
                  onClick={(event) => {
                    event.preventDefault();
                    let animeName = anime.title;
                    animeName = animeName.replace(/\s+/g, "");
                    setImageUrl(anime.image_url);
                    console.log("image url original", anime.image_url);
                    console.log("image url", image_url);
                  }}
                  className={styles.move}
                >
                  <img src={anime.image_url} alt="anime" />
                  <div className={styles.size}>
                    <h5>
                      <b>{anime.title}</b>
                    </h5>
                  </div>
                </a>
              );
            })}
        {image_url ? (
          <Router>
// below commented approch first display the component on the same page and then redirects to the url
// but the props passed are lost !
//             <Link to="/anime/info">
  //            <AnimeInfo image_url={image_url} />
    //          {window.location.href = `/anime/info`}
     //       </Link>
            <Route
              path="/anime/info"
              render={() => <AnimeInfo image_url={image_url} />}
            />
          </Router>
        ) : null}
      </div>

export default TopAnime;

Following is the component, to whom I want to pass props and use the data passed to display (on a whole new page)!

import React, { useEffect, useState } from "react";
import styles from "./AnimeInfo.module.css";

  console.log("The data image props issss", props.image_url);

  return (
    <div className={styles.container}>
      <h1> I am info component</h1>
      <img src={props.image_url} alt="anime" />
    </div>
  );
};

export default AnimeInfo;

Abdullah Ch
  • 1,678
  • 1
  • 13
  • 31

3 Answers3

1

Why not use the state property in history.push()?

See it in action here

Tasos
  • 1,880
  • 13
  • 19
  • 1
    {useHistory} from "react-router-dom" did the work for me – Abdullah Ch Sep 24 '20 at 10:12
  • It is the same thing, you can either extract it from `useHistory` or access it from the component props if you wrap it with `withRouter` when you export the component! – Tasos Sep 24 '20 at 10:13
0

use the history package.

then create a file at 'src/history.js'

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

then in your component

import history from './history'

history.push({
  pathname: '/path',
  data_name: dataObject,
});

Then you can access the props in your other component:

this.props.location.data_name
Stephen Taylor
  • 798
  • 7
  • 19
0

Use render method in router

const renderComponent = (props, Component) => {
   // write logic if needed
   return <Component {...props} />
}

<Route path="/earner" render={(props) => renderComponent(props, Main)}/>
Avani Bataviya
  • 750
  • 1
  • 6
  • 20