In the Popup component, we call ReactDom with the createPortal method, the createPortal method expects 2 properties,Ī React component like the Port Component, this is important so that we can pass props if we need to.Ī place where we need to port to, here we will get the root element using our javascript document method. If you look at the image below, we imported ReactDOM as a default export, then we created a separate component (The Port component) we want to port. ![]() So in the image below, the index.html file is where ReactDom will render the HTML code you wrote., and now you want to Render a particular component(say popup) to the div with an ID of "popup".sit to sit as a sibling to the div with the ID of "root".Īnd you have to explicitely add that div, React won't add it though, □ The common use case for React Portal is that, imagine you want to render a component in another place say siblings with the root div(i.e the div with an ID of root) in the DOM and a child of Body Element, without altering where it is written, weather it is deeply nested or not, you need to port the component from where it was originally created to where you want to rendered it to be in the DOM. you can either import the name fragment component from React or you use agment or you use the shorthand version of it.Īt the end it saves us the stress of wrapping our jsx components with unwanted and unnecessary divs and also render a clean HTML code to the DOM.Īs you know, whatever code you are writing in React gets rendered in DOM through the div with an ID of "root" which is in your index.html file., and the rendering is done in the index.js file which is the entry point. The best solution is what React provided for us, React.Fragment and this is how to use it. Now, this is totally fine and will work well, but when you have many nested div's that are returning another unnecessary div and its being rendered to the DOM, it leads to something called the DIV soup.īasically this isn't good for Accessibility and this could break your styling., and rendering unwanted content in react isn't also good for your react performance. This is a JavaScript feature because you can only return one thing.īefore now, the work around for someone like me and others was to wrap my content with inside another div and make it the only root component. ![]() The limitation with JSX is that, you cannot return multiple root jsx, and it has to be just one. In React, we work with JSX, jsx is that code which you return from your react component.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |