skip to Main Content

I have this component:

function Div() {
    return (
        <div id="hello" ref={el => {
            console.log(el.id) // <empty string>
        }}/>
    )
}

I’d like to access the element’s attributes in the ref callback, but they all seem to have default values. I know I can do something hacky like this:

function Div() {
    return (
        <div id="hello" ref={el => {
            setTimeout(() => {
                console.log(el.id) // "hello"
            })
        }}/>
    )
}

Any downsides to this? Is there a better way or is this the canonical way? Couldn’t find this behavior in the docs.

2

Answers


  1. I don’t see any problem with the first approach, I tried your snippet here and it logged the id of the div.

    import { render } from "solid-js/web";
    
    function Div() {
        return (
            <div id="hello" ref={el => {
                console.log(el.id) // hello
            }}/>
        )
    }
    
    render(() => <Div />, document.getElementById("app")!);
    

    Maybe check how you are using Div for rendering.

    Login or Signup to reply.
  2. When a ref function is invoked the element is not inserted into the page yet, that is why any layout related values like width, height, position are 0.

    If you need those values you need to access the element after it inserted into the DOM using an onMount hook which is guaranteed to run after the element is inserted into to the DOM.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search