简体   繁体   中英

Setting the innerHTML of an already rendered elment in react.js to be a component

Am working with the ionic ui library in react.js and here is my code

 <IonTabBar slot="bottom">
      {page.tabs.map(tab => {
        const Icon = Icons[`${tab.icon}`];

        return (
          <IonTabButton>
            <Icon
              style={{
                fontSize: "20px"
              }}
            />
            <IonLabel
              style={{
                fontSize: "14px"
              }}
            >
              {" "}
              {tab.text}{" "}
            </IonLabel>
          </IonTabButton>
        );
      })}
    </IonTabBar>
  </IonTabs>

And when renders on the browser it has this

 <div>
  <div class="tabs-inner"> </div>
  <ion-tab-bar>
    <ion-tab-button>
      <svg>
       .....
      </svg>
      <ion-label>
        user
      </ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</div>

Now i would like to inject a component into the class "tabs-inner" so my soultion was to give the div a ref and find it using

 const tab = tabsRef.current.getElementsByClassName('tabs-inner')[0]

Now I would like to inject a component into the div with the tabs-inner class say

tab.innerHTML = 'am here'

That works but if I try

tab.innerHTML = <Mycomponent/>

it doesn't, am trying to set the innerHTML to be a tag so I can inject components into it.

Any ideas?

You can try to put your component to be rendered in the state of the Component and render it accordingly. In case if you do not want to render anything at a particular time, you can set that state key to null.

constrcutor(props) {
    super(props);
    this.state = {
        componentToRender: null
    };
}

componentDidMount() {
    setTimeout(() => {
        this.setState({
            componentToRender: <b>Hello World</b>
        });
    }, 1000);
}

render() {
    return (
        <div className="">
            { this.state.componentToRender }
        </div>
    );
}

In the above example, I am just setting the HTML after 1 second but you can set the data whenever you want it to be.

So after doing a bit of digging, I found a not so wise way to do it using the react-dom import hydrate

import { hydrate } from "react-dom";
.........
const tab = tabsRef.current.getElementsByClassName("tabs-inner")[0];
hydrate(
  <Canvas/>,
  tab
);

This works for most cases and would have worked cool for me but am using redux in my canvas container and it is generating other errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM