I'm new to react, and I have few question about some react expressions.
I was watching the video to learn how to drag and drop components. The code below works, but I got confused by these things.
- Why const variable bindLogoPos became a function inside div? (line 8, line 18)
- What does the three dot means in this code? (I've learned that three dots usually mean the rest of array or object. But I think bindLogoPos is not quite related to an array or object)
- What does it mean to use {...bindLogoPos()} like this way? Does it means to call function infinitely? Is this expression possible only in react?
import logo from './logo.svg';
import './App.css';
import {useState} from 'react';
import {useDrag} from 'react-use-gesture';
function App() {
const [logoPos, setLogoPos] = useState({x:0, y:0});
const bindLogoPos = useDrag((params)=>{
setLogoPos({
x: params.offset[0],
y: params.offset[1]
});
});
return (
<div className="App">
<header className="App-header">
<div {...bindLogoPos()} style={{
position:'relative',
top: logoPos.y,
left: logoPos.x,
}}>
<img src={logo} className="App-logo" alt="logo" />
</div>
////////more...
First of all, you got to understand how React works.
React renders your component whenever the internal state changes, so
bindLogoPos()would be called when the state of your component changes. Therefore, it won't be called infinitely, but only when the state of your component / app changes.Secondly, that
const x = () => {}is actually an assignment statement, and it assigns an anonymous function to a variable called bindLogoPos. Functions are first-class citizens in JavaScript (functional programming!), so that's why it works like that. Also, the reason why "const variable bindLogoPos became a function inside div" is becauseuseDragactually gets the function itself as an argument then returns a different function.Next, the three dots mean to put the result of that function as the entire
props. So in your case, it would mean to get a return value frombindLogoPosthen assign it aspropsto the HTML div element. Think of it like passing the entire props as the sole function argument instead of destructuring the object then passing it one by one.I hope this answers your question, and happy coding!