Using ref to find a nested element

Viewed 818

I'm using the gridjs-react library to create a table as follows:

<Grid
  columns={['Name', 'Email']}
  data={[
    ['John', 'john@example.com'],
    ['Mike', 'mike@gmail.com']
  ]}
  ref={tableRef}
  search={true}
  pagination={{
    enabled: true,
    limit: 1,
  }}
/>

However, I want to ultimately add an item to the dom to get this:

enter image description here

I thought about using ref but I couldn't get access to the following div since it is only rendered after the component Grid is mounted: (As far as I know)

enter image description here

2 Answers

You can access the grid reference in useEffect block when all it's content is rendered:

useEffect(()=> {
    const grid = ref.current.wrapper.current; //--> grid reference
    const header = grid.querySelector(".gridjs-head"); //--> grid header
    const itemContainer = document.createElement("div"); //--> new item container
    header.appendChild(itemContainer);
    ReactDOM.render(<Input />, itemContainer); //--> render new item inside header
  }, []);

You will need to use css to get the desired position inside the element.

Working example: https://stackblitz.com/edit/react-r5gsvw

Or just use a CSS solution for that component you want.

e.g.

<div style={{ position: 'relative'}}>
    <Grid 
    ....
    />

    <MySearchComponent style={{ position: 'absolute', top: 0, right: 0 }} />
</div>
Related