1

Consider this structure of app:

<App>
  <SideBar/>
  <ProductsInterface/>
</App>

ProductsInterface renders an component called ProductList. I have another component called Filter and it's props depend on ProductList. It means i have to render it inside there.The problem is that i need it to be aligned on left, right under sidebar, not in ProductsInterface component. I tried to move it left with css but i think there are methods like ReactDOM.render(which says that div is not an valid element for appending) which i can append that Filter under a component or an html element with.

daed dadad
  • 55
  • 1
  • 5

3 Answers3

2

Not that I recommend it, but you can use ReactDOM.createPortal to render a component anywhere in the dom:

<App>
  <SideBar/>
  <div id="filters"></div>
  <ProductsInterface/>
</App>

Filters.js

...
render () {
    return ReactDOM.createPortal( <div>...</div>, document.getElementById('filters'))
}

The first argument for createPortal is the JSX to be rendered and the second arg is the DOM element to render it in. BUT, I would recommend you use CSS to position it underneath the sidebar.

Chase DeAnda
  • 15,963
  • 3
  • 30
  • 41
0

A better approach would be using a state manager like redux. So you'd be able to get any part of the state in any component without a need to nest them into each other. Or maybe context api can help you to share some state between components.

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
0

If you're willing to refactor your app's component structure, you can create a common ancestor for <Filter /> and <ProductList/> that passes state to both components as props. So instead of having this:

<App>
    <SideBar/>
    <ProductsInterface>
        <ProductList>
            <Filter/>
        </ProductList>
    </ProductsInterface>
</App>

You would have something like this:

<App>
    <ProductInfo> //product-related state lives here
        <Sidebar/>
        <Filter/>
        <ProductsInterface>
            <ProductList/>
        </ProductsInterface>
    </ProductInfo>
</App>

This allows you to put the filter at the bottom of the sidebar, since the components are siblings. <Filter/> could then receive functions like filterProducts() as props from <ProductInfo/> (its immediate parent). This would look like the following in ProductInfo.js's render method:

<Filter propName="this.filterProducts"></Filter>

Then set up your onClicks in <Filter/> to call the function from its props, which will update the state in <ProductInfo/> and by extension the contents of <ProductList/> (since it's receiving the <ProductInfo/> state as props).

This pattern is called lifting state up and is fairly common in React applications. I would definitely recommend researching it further as you develop your strategy for organizing your component tree.

A. Lamansky
  • 284
  • 2
  • 7