Home > Net >  jQuery .load() equivalent in REACT
jQuery .load() equivalent in REACT

Time:10-11

I am learning React and trying to migrate a PHP jQuery Page to React (without jQuery). However, due to the complexity of the page I won't be able to fully migrate all the page at once. Therefore, I need to start migrating a few of the pages in React already while loading some of the old pages just as content.

I would like to have my Navigation, Footer, ... in React already while still using the content of the old page. I thought something like the jQuery $(".content").load(url ' .content') is what I am looking for, but without using jQuery.

In React I built something like this:

import  React, { useState, useEffect } from "react";

export default function ContentLoader(params){
    const [content, setContent] = React.useState("");

    function load(url) {
        fetch(url).then(res => {
            let html = res.text();
            setContent(html.querySelector(".content")); 
        });
    }
    
    useEffect(() => {
        load(params.url);
    });

    return(
        <div className="content">
            {content}
        </div>
    )
}

However, I am getting a error Unhandled Rejection (TypeError): html.querySelector is not a function. (In 'html.querySelector(".content")', 'html.querySelector' is undefined)

Just for context, the element is integrated into another element like this:

 <Route
    path='/stackoverflow'
    element={
        <ContentLoader url='http://myurl.com/stackoverflow' />
    }
 />

Thank you so much in advance!

CodePudding user response:

Your main problem is that res.text() resolves with a plain string, not an HTML document.

You're also going to run into problems trying to insert an HTML fragment into JSX.

The first problem can be solved by using the Edit lucid-snyder-byhlhd


You could also use a ref element and append the parsed document fragment

const contentRef = useRef(null);

useEffect(() => {
  load(url, ".content")
    .then((content) => {
      // empty out any previous content
      contentRef.current.innerHTML = "";

      contentRef.current.append(content);
    })
    .catch(console.error);
}, [url]);

return <div className="content" ref={contentRef}></div>;
  • Related