Home > Mobile >  React routing loop - show the exact information according to route link
React routing loop - show the exact information according to route link

Time:10-28

I have an array of 3 items.

export default [
     {
          id: "90",
          symbol: "BTC",
          name: "Bitcoin",
          nameid: "bitcoin",
          rank: 1,
          price_usd: "58976.61",
     },
     {
          id: "80",
          symbol: "ETH",
          name: "Ethereum",
          nameid: "ethereum",
          rank: 2,
          price_usd: "4021.22",
     },
     {
          id: "2710",
          symbol: "BNB",
          name: "Binance Coin",
          nameid: "binance-coin",
          rank: 3,
          price_usd: "455.61",
     },
];

I made a component that makes a list with all of the 3 items using map function.

function CoinList() {
  return (
    <div className="bg-gray-800 w-56 h-56 text-white p-4 rounded-2xl mt-12">
       {users.map((user) => {
          return (
           <Link to={user.symbol}>
             <div className="my-3">
                Coin Name - {user.symbol}
                <p>Price - {user.price_usd}</p>
                   </div>
                      </Link>
                    );
               })}
          </div>
     );
}

I made a routing that when pressing on a coin, will route to mywebsite.com/{coin.symbol} On each routed page I want to show a "Coin Page" with all the information.

My Coin Page looks like this:

function CoinPage() {
     return (
          <div className="bg-gray-800 w-56 h-56 text-white p-4 rounded-2xl mt-12">
               <p>{users[0].name}</p>
               <p>{users[0].price_usd}</p>
          </div>
     );
}

But of course it shows only the information of the first coin, which is Bitcoin.

How can I write the code in order to show Bitcoin information if the link is /BTC or Ethereum if the link is /ETH and so on?

CodePudding user response:

You most probably need to look into the useParams hook from react-router. https://reactrouter.com/web/api/Hooks/useparams

Assuming you have a route like

<Route path="/:coinName">
    <CoinPage />
</Route>

Then try:

function CoinPage() {
 const {coinName} = useParams();
 return (
      <div className="bg-gray-800 w-56 h-56 text-white p-4 rounded-2xl mt-12">
           <p>{users[0].name}</p>
           <p>{users[0].price_usd}</p>
           <p>{displayInfo(cointName)}</p>
      </div>
 );

}

CodePudding user response:

You should match the coin symbol from the HTML link with the index from your array. If you are on mywebsite.com/BTC, then, you should see the corresponding index of that coin in your array.

  • Related