I have a webpage that displays a list of buttons and corresponding iframe components. Each time a new button is clicked, a new iframe is displayed and the existing one is removed.
Here is the iframe component:
const IframeComp = ({ button }) => {
return (
<iframe src={button}></iframe>
)
}
export default IframeComp
I am loading all the possible iframes--as strings--into a list in app.jsx
when the app loads like so:
const [iframeComponents, setIframeComponents] = useState()
useEffect(() => {
function loadIframes() {
let iframes = {}
for (const iframeUrl of constants.buttonUrls) {
const iframe = `<IframeComp button=${iframeUrl}></IframeComp>`
iframes[iframeUrl] = iframe
}
setIframeComponents(iframes)
}
loadIframes()
}, []);
And passing the iframeComponents
to the iframe display page file which checks which button is pressed and renders the appropriate iframe.
Of course, the iframes are getting rendered as strings right now. Is there a way to load/render these IframeComp components in the app.jsx as actual components/html, store them in a list, and then simply display them downstream based on button click?
Alternatively, I have tried using html-react-parser
library to simply render the strings as html in the iframe display page file, but this doesn't work as it lowercases the strings, and they'd also have to take time to render on each button click.
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.
7 Ways to Implement Conditional Rendering in React Applications | DigitalOcean.
Why not use component directly?
const [iframeComponents, setIframeComponents] = useState();
useEffect(() => {
function loadIframes() {
let iframes = {};
for (const iframeUrl of constants.buttonUrls) {
const iframe = <IframeComp button={iframeUrl}></IframeComp>;
iframes[iframeUrl] = iframe;
}
setIframeComponents(iframes);
}
loadIframes();
}, []);
What is your actual code for change iframe by button?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With