Home > Blockchain >  How can I call react component in setContent leaflet?
How can I call react component in setContent leaflet?

Time:11-16

How can I call react js component in setContent? Actually, I want to insert a button in popup leaflet which click on it and call a react component. I know "reactDomserver.rendertostring" is a method to string a component to HTML. But there is no able to click on button to call another component when the component change to HTML. It would be grateful if anyone can help me.

Sample code is above:

            // adding mouse hover popup
            hoverPopup = L.popup({ closeButton: false, className: "hover-popup" });
            hoverPopup.setContent(`<div>
                <div >
                <ul >
                  
                  <li >
                        <button onclick={()=>CustomComponent()}> Test </button> /////// Here is Error
                  </li>
                 
                </div>`);
            marker.on('mouseover', function (e) {
                hoverPopup.setLatLng(e.latlng);
                hoverPopup.openOn(MAP);

            });

CodePudding user response:

First, you need to change "onclick" function inside the Html content. It's pure html and not the correct syntax.

Wrong:

onclick={()=>CustomComponent()}

Correct:

onclick="CustomComponent()"

After that, you can listen content changes with useEffect and if content exist you can add click event with pure javascript. Like this;

Demo: https://codesandbox.io/s/stackoverflow-69979099-35hyb?file=/src/App.js

export default function App() {
  const [content, setContent] = useState(null);
  useEffect(() => {
    if (content) {
      document.getElementById("btn").onclick = (e) => {
        e.preventDefault();
        eval(e.target.getAttribute("onclick"));
      };
    }
  }, [content]);
  const CustomComponent = () => {
    alert("Custom Component Func!");
  };
  return (
    <div className="App">
      <button onClick={() => {setContent(`<div>
        <div >
        <ul >
          
          <li >
                <button id="btn" onclick="CustomComponent()"> Test </button>
          </li>
         
        </div>`);
        }}
      >
        Show Content
      </button>
      <button>Hide Content</button>
      <hr />
      {content && <div dangerouslySetInnerHTML={{ __html: content }} />}
      <div></div>
    </div>
  );
}
  • Related