Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get rowIndex in Reactjs?

I have a table using normal HTML in reactjs:

 const [user, setUser] = useState(null);

 useEffect(() => {
    axios
      .get("http://localhost:8080/api/users")
      .then((response) => {
        setUser(response.data);
      });
  }, [url]);

const [rowIndex, setRowIndex] = useState("");

if (user) {
    return (
      <div>
        <table className="table">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Age</th>
              <th scope="col">Department</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody>
            {user.map((item) => (
              <tr>
                <td>{item.name}</td>
                <td>{item.age}</td>
                <td>{item.department}</td>
                <td><button>Click</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

If in Javascript, I can simply set <tr onclick="getIndex(this)"> and calling function getIndex(x) {console.log(x.rowIndex)} to get the row number.

But it’s not working in ReactJS. How can I get the rowIndex in ReactJS?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use index inside your map method and then use this variable inside your button’s onClick method

 const [user, setUser] = useState(null);

 useEffect(() => {
    axios
      .get("http://localhost:8080/api/users")
      .then((response) => {
        setUser(response.data);
      });
  }, [url]);

const [rowIndex, setRowIndex] = useState("");

if (user) {
    return (
      <div>
        <table className="table">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Age</th>
              <th scope="col">Department</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody>
            {user.map((item, index) => (
              <tr>
                <td>{item.name}</td>
                <td>{item.age}</td>
                <td>{item.department}</td>
                <td><button onclick={() => setRowIndex(index)}>Click</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading