Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save components to a list and then conditionally render

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.

like image 820
yalpsid eman Avatar asked Nov 24 '21 19:11

yalpsid eman


People also ask

What is conditional rendering?

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.

How many ways you can conditionally render in React?

7 Ways to Implement Conditional Rendering in React Applications | DigitalOcean.


Video Answer


1 Answers

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?

like image 105
fixiabis Avatar answered Oct 30 '22 07:10

fixiabis