How to make <li> switch to another page on click in react.js

Viewed 25

I have to fetch data from an API and display it as a list, and then when you click on an item in the list it should take you to another page with details about that item. I don't know how to make the li element take me to another page with details

This is my app.js

import React, { useState, useEffect } from "react";
import CharacterList from "./Components/CharacterList";
import Navbar from "./Components/Navbar";

function App() {
  const [characters, setCharacters] = useState([]);

  const callBreakingBadAPI = async () => {
    const url = `https://www.breakingbadapi.com/api/characters?name`;
    const resp = await fetch(url);
    const data = await resp.json();
    setCharacters(data);
  };

  useEffect(() => {
    callBreakingBadAPI();
  }, []);

  return (
    <div className="container">
      <Navbar />
      {<CharacterList characters={characters} />}
    </div>
  );
}

export default App;

this is characterList.js
import React from "react";
import CharacterListItem from "./CharacterListItem";

const CharacterList = ({ characters }) => {
  return (
    <section>
      {characters.map((character) => (
        <CharacterListItem character={character} key={character.char_id} />
      ))}
    </section>
  );
};

export default CharacterList;

And this is my CharacterListItem.JS

import React from "react";

const CharacterListItem = ({ character }) => {
  return (
    <ul>
      <li>Name: {character.name}</li>
    </ul>
  );
};

export default CharacterListItem;

I have a characterinfo folder inside my components folder with characterInfo.js where I want to switch to show details about the clicked item.

2 Answers

You can add a onClick handler to your li

const history = useHistory()

<li onClick={() => history.push(/* your url */)}>
  Name: {character.name}
</li>

It is recommended not to add onClick listeners to non-interactable html elements for accessibility. If you still want to add the listener, you will have to look at how to make the element accessible. For example, adding tabindex="1" for keyboard users, etc.

Best element type for this usecase would be link (or in some cases, button)

<li>
  <Link to={/* your url */}>
    Name: {character.name}
  </Link>
</li>

You can send the character details from CharacterListItem.js through Link state.

import { Link } from "react-router-dom";

const CharacterList = ({ character }) => {
  return (
      <Link to="/character-info" state={{data: character}}  >Name: {character.name}</Link>
  ); 
};

and from charactorInfo.js, data can be recieved using useLocation hook.

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

const CharacterInfo = () => {

const location = useLocation();
const character = location.state?.data;

console.log(character);

return (
<div>
  {/* Display character here */}
</div>)
}

Related