Search code examples
javascriptreactjsreact-nativecomponentsjsx

How to render string as custom React component?


So I have this code

ReactDom.render(<Home />, document.getElementById("main"));

This works perfectly and it renders Home component. I want to make this code dynamic instead Home component, it can be any component like Apartment or Building component.

I have tried to do this by the following code.

const tag = `<${main} />`;
ReactDom.render(tag, document.getElementById("main"));

This doesn't work.

I would like to know if it is possible. I would prefer to do this without any third party library.


Solution

  • What I would do as also mentioned in the comment section is creating first an <App /> component and handling there which one to render in your screen. This won't render all the components as you might expect based on your comment.

    For example in the <App /> component based on a string value you can render different components. This string value can be manipulated with button components' onClick handlers what I leave it to you how to deal with.

    The main <App /> component would look like this then:

    import React, { useState } from 'react';
    // import other components
    
    function App() {
       const [current, setCurrent] = useState('home');
    
       if (current === 'home') { return <Home /> }
       else if (current === 'contact') { return <Contact /> }
       else { return <DifferentComponent /> }
    }
    
    export default App;
    

    The index.js would be like the following:

    ReactDOM.render(<App />, document.getElementById('root'));
    

    At the end you can create different buttons in your return where you can call setCurrent in order to manipulate which one to render.

    Or as I suggested in the comments like a second option, you can go with react-router, this will help you to render different components based on the current route. Take a look at here to this good quick start training if you would like achieve that.

    I hope this explanation helps!