Search code examples
reactjsaxiosreact-tablereact-table-v7

How do I get the Id when clicked on the first row in React JS?


I am pretty new to React and I was following a tutorial to build a react-table, but I wanted to go one step further and see if I can make the first row or cell clickable and get the ID of that cell. However, I am unable to achieve that. I am not sure if this has already been answered, but I could not find any answer.

App.js

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    getData();
  }, []);
  const getData = async () => {
    const result = await axios
      .get("https://api.tvmaze.com/search/shows?q=spider")
      .then((response) => {
        setData(response.data);
        console.log(response.data);
      });

    return result;
  };

  const columns = useMemo(
    () => [
      {
        Header: "Tv Show",
        columns: [
        
          {
            Header: "Name",
            accessor: "show.name",
          },
          {
            Header: "Type",
            accessor: "show.type",
          },
        ],
      },

Table.js

 return (
          <tr {...row.getRowProps()} data={columns} onClick={checkButton}>

This is part of the API

[{"score":20.77334,"show":{"id":4107,"url":"https://www.tvmaze.com/shows/4107/spider-man","name":"Spider-Man","type":"Animation","language":"English","genres":["Action","Adventure","Children"],"status":"Ended","runtime":30,"premiered":"1967-09-09","officialSite":null,

Tbh I do not know what should be in the checkButton function, I have so many things to get the data, but I am unable to do so. I really appreciate your guidance. Thank you !


Solution

  • You are right to use onClick on the table rows. Just add a simple function to check the row index:

    const logDataIfFirstRowClicked = (row) => {
        if (row.index === 0) {
          console.log("FIRST ROW CLICKED");
          console.log(row); // returns row object: {id: "0", original: Object, index: 0, depth: 0, cells: Array(2)…} 
          console.log(row.original) // returns the data from the row ex: {actor: "Johnny Depp", movie: "Pirates of the Carribean 1"}
        }
      };
    

    and pass it to your table row:

    rows.map(row => ({
      <tr {...row.getRowProps()} onClick={() => logDataIfFirstRowClicked(row)}>
    }))
    

    You can also use the Cell render method in the Column definition to add an on click. If you only want the first cell of each row to return its value on click, it could look like this:

    const columns = useMemo(
        () => [
          {
            Header: "Tv Show",
            columns: [
            
              {
                Header: "Name",
                accessor: "show.name",
              },
              {
                Header: "Type",
                accessor: "show.type",
              },
            ],
            // Set the custom cell render here:
            Cell: (cell) => (
              <button
                // add on click to your custom cell
                onClick={() => console.log(cell.value)}
              >
                {" "}
                {cell.value}{" "}
              </button>
            )
          },
        ]
    

    Check out this DEMO and this example on React-Table's GitHub

    Row Properties section of React-Table docs