Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  140] [ 5]  / answers: 1 / hits: 17789  / 5 Years ago, wed, february 13, 2019, 12:00:00

I'm working on a React app and am trying to use ReactDOM.createPortal() to add html content to a div that is outside the component (called ToDoItem).



{ReactDOM.createPortal(
<Route path={`/profile/project/${this.props.project._id}`} render={() =>
<ProjectView project={this.props.project}/>} />,
document.getElementById('tasks')
)}


None of the HTML in the public folder is predefined - it is all dynamically created.



I think this could be the cause of the error: React tries to add HTML to the div with the id of tasks which, but the div is not loaded into the DOM before this happens?



If this method is incorrect, is there any other method I can use append html content to another div outside the component?



Some other info: the component from which I tried to run this method is a stateless component, not a class component.



This is the error:



enter


More From » reactjs

 Answers
10

You can wait until the DOM is ready using React.useEffect, and then you call ReactDOM.createPortal:


function Component() { 
const [domReady, setDomReady] = React.useState(false)

React.useEffect(() => {
setDomReady(true)
})

return domReady
? ReactDOM.createPortal(<div>Your Component</div>, document.getElementById('container-id'))
: null
}

[#52608] Friday, February 8, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnaj

Total Points: 490
Total Questions: 109
Total Answers: 104

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;