'How to get a link element from one list in the react component and run a link whit out clicking?

0

I have a list of messages and I am trying to get some link from that message if it exists there (and store it in studentlink const) this will happen in an event listener. getElemenBy tag and id and the name don't work, I don't know why! what is your idea? in the next step, I need to run that link whit out clicking, automatically but I didn't find any method or solution yet, how is possible?

import React from "react";
import { connect } from "react-redux";
import reactDom from "react-dom";

function MessageList(props) {
  const handleLoad = (e) => {
    if (listItems !== "") {
      let studentlink = document.getElementById("myAnchor").href;
      window.location.href = studentlink;

      alert(`${studentlink}`);
    } else {
      console.log(window.location.href);
    }
  };

  React.useEffect(() => {
    window.addEventListener("load", handleLoad);

    // cleanup this component
    return () => {
      window.removeEventListener("load", handleLoad);
    };
  }, []);

  const arr = props.studentmessage;
  const listItems = arr.map((message, index) => (
    <li key={index} id="myAnchor">
      {message}
    </li>
  ));
  return (
    <section>
      <div className="commentbox">
        <ul>{listItems}</ul>
      </div>
    </section>
  );
}

const mapStatetoprops = (state) => {
  return {
    studentmessage: state.message,
  };
};

export default connect(mapStatetoprops)(MessageList);



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source