2

I have a NextJS application, with the following page:

Page:

import Layout from "@/components/app/Layout";
import Sidebar from "@/components/app/Sidebar";

export default function SiteIndex() {
  return (
    <Layout>
      <div className="flex">
        <Sidebar />
        <div className="m-5">
            <iframe src="/page.htm"></iframe>
        </div>
      </div>

    </Layout>
  );
}

This page has an iframe, a parent Layout component, and one more component called Sidebar.

Parent Layout:

export default function Layout({ children }) {
    return (
        <div>
            <div class="h-12 bg-gray-200 flex">
                <div className="m-2 grow">Parent Layout</div>
                <button className="bg-blue-500 text-white p-3">Reload iFrame Button</button>
            </div>
            <div>{children}</div>
        </div>
    )
}

Sidebar:

export default function Sidebar() {

    return (
        <div className="w-64 border border-r-100 m-5">
            <div>Sidebar</div>

            <button className="bg-blue-500 text-white p-3">Reload iFrame Button</button>
        </div>
    )
}

Both Layout and Sidebar have a button. I want to be able to reload the iframe on the press of any of those buttons. How can I achieve this in react/nextjs project? primarily I'm looking for the best way to reload an iFrame within reactjs.

asanas
  • 3,782
  • 11
  • 43
  • 72

1 Answers1

2

Would it work for your application to add a key={keyValue} to the iframe? You can then set the value of that key whenever the button gets pressed. This should cause a re-render.

export default function SiteIndex() {
const [keyValue, setKeyValue] = useState(0);

  return (
    <Layout onButtonClick={() => setKeyValue(keyValue + 1)} >
      <div className="flex">
        <Sidebar onButtonClick={() => setKeyValue(keyValue + 1)}  />
        <div className="m-5">
            <iframe src="/page.htm" key={keyValue}></iframe>
        </div>
      </div>
    </Layout>
  );
}

And in your component

jolo
  • 605
  • 1
  • 5
  • 12