2

I'm having a problem where I want the information that is being passed on a page to be sent to another page, this other page I say is like a single page.

I've already tried to pass the parameters of this page to another with props, params, but without any success.

I believe it is something very simple, but it left me without a solution

Homepage.jsx

import React, {useEffect, useState} from 'react';
import * as Styled from './styles';
import OwlCarousel from 'react-owl-carousel';
import 'owl.carousel/dist/assets/owl.carousel.css';
import 'owl.carousel/dist/assets/owl.theme.default.css';
import { FaStar,FaInfoCircle } from "react-icons/fa";
import { NavLink } from 'react-router-dom';
import SinglePage from '../SinglePage';

export default function Home() {
  const [data, setData] = useState([]);  


  useEffect(() => {
    fetch('https://api.rawg.io/api/games?key=328c7603ac77465895cf471fdbba8270')
     .then((res) => res.json())
     .then((data) => {
       setData(data.results);                  
     })
     .catch((err) => {
       console.log(err);
     });
  }, []);

  return (
    <>
      <Styled.Container>                     
        <div className="boxSite">
          <div className="boxBrowse">
            <div className="boxAll">
              <OwlCarousel className='owl-theme' loop margin={0} items={6} center={true} dots= 
              {false}>                
                {data.map((games)=> (
                  <>
                    <div className="produto" key={games.id} layoutId={games.id}>
                      <div className="imagemGame" style={{backgroundImage: 
                    `url(${games.background_image})`}}>
                        <div className="information">                          
                          <NavLink to={{                            
                              pathname:`/single-game/${games.slug}`,                            
                            }}
                          >                          
                            <span>
                              <FaInfoCircle/>                            
                            </span>                          
                          </NavLink>    

                          <SinglePage name={games.name} />
                        </div>
                        <div className="classificacao">
                          <span> Avaliação <b> {games.rating} </b></span>
                          <span> <FaStar /></span>
                        </div>
                      </div>
                    </div>
                  </>
                ))}                  
              </OwlCarousel>
            </div>
          </div>
        </div>        
      </Styled.Container>
    </>
  )
}

SinglePage.jsx

import React from 'react';
import * as Styled from './styles';

export default function SinglePage(props) {
  return (
    <>
      <h1>NAME OF THE GAME : {props.name}</h1>
    </>
  )
}

Yes, I stopped here, please can someone help me?

Information is appearing on the Homepage, but not on the single page

enter image description here enter image description here

0

4 Answers 4

1
  1. Import component into Homepage
import SinglePage from './your-single-page-file';
  1. Use the tag and pass a parameter on the JSX
<SinglePage name={data.variableNeeded}  />
  1. On the SinglePage function add the props parameter and use it like this:
import React from 'react';
import * as Styled from './styles';


 export default function SinglePage(props) {
 return (
    <>
     <h1>NAME OF THE GAME : {props.name}</h1>
   </>
 )
 }
Sign up to request clarification or add additional context in comments.

1 Comment

I tried to do as you mentioned, but it didn't work. I edited the question showing the result that appeared
1

In this case, if you're using version 5 or earlier of router-dom you can pass the data via state, using history:

Change this:

import { NavLink } from 'react-router-dom';

return (
  <NavLink to={{                            
    pathname:`/single-game/${games.slug}`,                            
   }}>                          
    <span>
      <FaInfoCircle/>                            
    </span>                          
  </NavLink>
)

To this:

import { useHistory } from 'react-router-dom';

const history = useHistory();

return (
  <button
    onClick(() => history.push(`/single-game/${games.slug}`,{
      foo: 'bar',
      nameGame,
    }))
  >                          
    <span>
      <FaInfoCircle/>                            
    </span>                          
  </button>
)

And on your page you can get the data via props, like:

import React from 'react';

export default function SinglePage(props) {
  const { nameGame } = props.location.state;

  return (
    <>
     <h1>NAME OF THE GAME : {nameGame}</h1>
    </>
  )
}

3 Comments

I'm using version 6, do you have any solution for this version? I tried using your answer but it didn't work for me. I even edited the question, showing the result that was..
On version 6 you'll need to use 'navigation' import { useNavigate } from 'react-router-dom' const navigate = useNavigate(); navigate('/other-page', { state: { foo: 'bar', nameGame } });
@FelipeGodoy Don't use a button and the history or navigate functions, just send the state via the link component you are already rendering.
0

It depends on your needs.

  • If you need to access a lot of data over several pages, you should use a state management library like Redux.
  • If it's only simple data, you can pass it as query parameters to your page.
  • If it's a bit more complexe, you can use the session / local storage.

But it's a bit hard to know what to recommend you exactly without more info about what you want to achieve exactly.

Comments

0

Since you only included the component that has a single data state that is mapped and renders some links I'll assume it is the games object you want to send to the linked route. Pass the data in route state via the NavLink component.

See NavLink and Link

interface LinkProps
  extends Omit<
    React.AnchorHTMLAttributes<HTMLAnchorElement>,
    "href"
  > {
  replace?: boolean;
  state?: any;
  to: To;
  reloadDocument?: boolean;
}

Route state is sent along on the state prop of a link component.

Example:

{data.map((games) => (
  <div className="produto" key={games.id} layoutId={games.id}>
    <div
      ....
    >
      <div className="information">                          
        <NavLink
          to={`/single-game/${games.slug}`}
          state={{ games }} // <-- pass route state
        >                          
          <span>
            <FaInfoCircle/>                            
          </span>                          
        </NavLink>    

        <SinglePage name={games.name} />   
                            
      </div>
      ....
    </div>
  </div>
))}

In the receiving component use the useLocation hook to access the passed route state.

Example:

import { useLocation } from 'react-router-dom';

export default function SinglePage() {
  const { state } = useLocation();
  const { games } = state || {};

  ...

  return (
    <>
      <h1>NAME OF THE GAME : {games.name}</h1>
    </>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.