How to check if the element is present using react?

Viewed 1678

How can I check if an element is present in the DOM or not, using React?

I have a popup that is displayed throughout the application when items are 0 and the user clicks a button. It's created by a context provider that is wrapped around the App component.

There is an add button that gets displayed in some page "/items".

const root = () => {
    <PopupContextProvider>
        <App/>
    </PopupContextProvider>
}


export const PopupContextProvider = ({ children }: any) => {
    return (
        <popupContext.Provider value={context}>
            {children}
            {(condition1 || condition2) && (
                <Popup onHide={dismiss} />
            )}
        </popupContext.Provider>
    );
}

function App() {
    return (
        <Route path="/items">
            <Drawer/>
        />
        //other routes
    );
}



function Drawer() {
    return (
        <ButtonElement/> //this is a styled div component and i want to check if this element is 
        //present in dom at the sametime when popup is there in dom 
    );
}

What I want to do?

I want to check if the ButtonElement is there in the DOM at the same time as the popup.

The ways that I have thought:

  • add an id to button element and check if it is present using document.getelementbyid (last option for me)
  • using ref, but I'm not sure how to do it

I want to use a ref to button element, but I don't know how to pass it to context.

What would be the best way to do this?

1 Answers

Use the useRef hook and pass it down to the child component. It'll be undefined

Assuming you're defining const popupContext = React.createContext(undefined); somewhere, roughly this should work:

const PopupContextProvider = ({ children }: any) => {
    const popupRef = useRef(null);
    return (
        <popupContext.Provider value={popupRef}>
            {children}
            {(condition1 || condition2) && (
                <Popup onHide={dismiss} ref={popupRef}/>
            )}
        </popupContext.Provider>
    );
}


const Drawer = () => {
    return (
        <popupContext.Consumer>
            {value => (value !== undefined)
                ? <ButtonElement popup={true}/>
                : <ButtonElement/> 
            }
        </popupContext.Consumer>
    );
}

More info about context usage here: https://reactjs.org/docs/context.html#reactcreatecontext

Related