Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is node => {this.node = node } in React

Tags:

reactjs

I am new in React I would like to create dropdown with outside click to close

I end up with something like

ref={(node) => {this.node = node;}}

what does it mean can someone explain this line of code ?

like image 781
GartO Avatar asked Dec 24 '18 05:12

GartO


People also ask

What does => means in React?

The () => { ... } is the function. It's an ES6-style "arrow" function expression. These are like function expressions ( tick = function() { ... } ) except that the this value within the function is inherited from the context in which it's defined rather than being set when the function is called.

What are nodes in React?

A React node is defined as: a light, stateless, immutable, virtual representation of a DOM node. React nodes are not real DOM nodes (e.g., text or element nodes) themselves, but a representation of a potential DOM node.

What is React VS node?

React and Node. js are two of the most popular open-source JavaScript frameworks, but they differ in their approach to a number of tasks. For example, while React is mostly used for building websites and user interfaces, Node enables developers to build server-side code.

What is import type node from React?

This means it's a function that takes no parameters and returns a react Node . Types help with development by letting the computer analyze the code better, and point out bugs sooner (before even running the code)


1 Answers

This is ref function, a low-level way to assign a ref. It assigns a reference to this.node property after a component or element was mounted.

A recommended way is to use:

this.nodeRef = React.createRef();

...

<Comp ref={this.nodeRef}/>

A ref becomes available as this.nodeRef.current after a component was mounted. The use of this.nodeRef object that can be passed by reference is a way to avoid some common problems that can appear with this.node.

like image 114
Estus Flask Avatar answered Oct 06 '22 00:10

Estus Flask