2

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139

2 Answers2

2

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!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

You can create a component to render each name you pass set in state, This will render all the components as you might expect based on your props.

for example you can write this component : Render.js

import React, { useState } from 'react';
// import other components

export default (props) => {
  const [current, setCurrent] = useState('home');
  const App= {
    home: Home,
    apartment: Apartment ,
    building: Building,
    ...
  };

  let Render = App[current] || Home;

  return <Render {...props}   />;
};

The index.js would be like the following:

ReactDOM.render(<Render/>, document.getElementById('root'));
Hamid Shoja
  • 3,838
  • 4
  • 30
  • 45