vincedd
vincedd

Reputation: 141

how to use ref in stateless functions?

I'm new for react, there is my code

It's printing undefined in console, how to make it work?

const Example = () => {
  let node;
  return (
    <div>
      <p ref={el => (node = el)}>hello world!</p>
        {console.log(node)}
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);

Upvotes: 2

Views: 68

Answers (1)

javad bat
javad bat

Reputation: 5226

it is because the block you log the node in it is different from function block if you run below code :

const Example = () => {
  let node;
  return (
    <div>
      <p
        ref={el => {
          node = el;
          console.log(node);
        }}
      >
        hello world!
      </p>
      {console.log(node)}
    </div>
  );
};

you will see the node ref as <p>hello world!</p>in your console . if you want to use ref your way is correct you just need to set it to the proper variable with good scope for example use window.node test link is: https://codesandbox.io/s/kxj92vojmo.
the best solution to your problem is using state manager as MobX to share ref and states between your view and viewModel

Upvotes: 1

Related Questions