Get id of the closest element

115 Views Asked by At

Could anyone help to find out the way that i'm using for accessing the closest element id is right and if there is any issues by doing this. I'm using sitecore headless approach. So there is no way to send any props to child component by our own. If this approach is not a proper way is there any way to send placeholder name to the child component in sitecore. If that is possible there is no need of accessing DOM.

parent component

<div className={styles.xyz} id="xyz">
<Placeholder name='jss-content66' rendering={props.rendering}/>
</div>

Child Component

import {useEffect, useRef} from 'react';
    import {LinkBoxDataConfig} from 'src/models/linkBox';
    import {formatLinkBoxData } from 'src/helpers/component.helper';
    import styles from './Linkbox.module.scss';
    
    export default function Linkbox (props: any) { 
    const linkData =  formatLinkBoxData(props);
    const nodeRef = useRef(null);
    
    useEffect (() => {
        const child = nodeRef.current; 
        if (child !== null) {
            const closest = child.parentNode.closest('div').id;
            console.log(closest)
        }
    },[]);
    return (
        <div
        className={styles.linkBox_container}
        ref={nodeRef}
        >
            {linkData && linkData.title && linkData.title !== '' ? (
                <div className={styles.linkBox_heading_container}>
                    <div className={styles.linkBox_heading}>{linkData.title} </div>
                </div>
            ):''
            }
        </div>
    );
    }
0

There are 0 best solutions below