最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass parameters to another page in React JS - Stack Overflow

programmeradmin2浏览0评论

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('')
     .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

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

Share Improve this question edited May 18, 2022 at 5:12 Drew Reese 204k18 gold badges246 silver badges274 bronze badges asked May 17, 2022 at 21:30 Felipe GodoyFelipe Godoy 731 silver badge8 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 1
  1. Import ponent 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>
   </>
 )
 }

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>
    </>
  )
}

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 plexe, you can use the session / local storage.

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

Since you only included the ponent 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 ponent.

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 ponent.

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 ponent 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>
    </>
  );
}
发布评论

评论列表(0)

  1. 暂无评论