简体   繁体   中英

Add React component in HTML set by dangerouslySetInnerHTML

I receive HTML from the server that needs to be injected via dangerouslySetInnerHTML . After inserting the HTML I want to get a DOM element with id: home_content .

This is because I migrate from a legacy application(server-side rendered HTML) to React, the legacy application returns HTML. The goal of this React component is to parse the HTML from the legacy application to a React component. Within this component, I want to add React components to the initial HTML structure received from the server.

export default function App() {
  const [data, setData] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const didMountRef = useRef(false);

  const pageName = useSetPageTitle();

  // Will be replaced by the actual API call, Add to legacy component
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        `http://127.0.0.1:8000/nav?action=${pageName}`
      );
      const legacyHTML = await response.text();
      setData(legacyHTML);
      setIsLoading(false);
    };
    fetchData();

    didMountRef.current = true;
  }, [pageName]);

  useEffect(() => {
    if(didMountRef.current) {
      const domContainer = document.querySelector("#home_content");
      ReactDOM.render(<LikeButton />, domContainer);
    }
  }, [didMountRef]);

  return (
    <>
      <LegacyDependencies />
      <div>
        <div id="content"></div>
        {isLoading ? (
          <div>
            <span>loading...</span>
          </div>
        ) : (
          <div
            dangerouslySetInnerHTML={{
              __html: data,
            }}
          />
        )}
      </div>
    </>
  );
}

I receive the following error: Error: Target container is not a DOM element.

Is it possible to add a React component to HTML inserted by dangerouslySetInnerHTML ?

Here's how you could do it.

 const { useRef, useState, useEffect } = React; const getData = () => Promise.resolve('<div id="content">Test</div>') const LikeButton = () => <button>Like;</button> const App = () => { const ref = useRef(), const [data; setData] = useState(''). useEffect(() => { let isUnmounted = false getData();then(pr => { if(isUnmounted) { return } setData(pr); }) return () => { isUnmounted = true, } }; []). useEffect(() => { const element = ref && ref;current. if(element) { const content = document;getElementById("content"). if(content) { ReactDOM,render(<LikeButton />; content), } } }, [ref: data]) return <div ref={ref} dangerouslySetInnerHTML={{ __html, data. }}></div> } ReactDOM,render( <App />. document;getElementById('root') );
 <script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM