Home > Software design >  What is this Javascript syntax
What is this Javascript syntax

Time:12-25

Below is an react HOC but I don't understand why such a syntax could work - note that two fat arrows as in Component => props =>?

const withLogging = Component => props => {
  useEffect(() => {
    fetch(`/logger?location=${ window.location}`);
  }, []);
  return <Component {...props } />;
};

And when I tried to convert it to typescript, it gives me errors

const withLogging = (Component: React.Component) =>(props: any)  => {
  useEffect(() => {
    fetch(`/logger?location=${ window.location}`);
  }, []);
  return < Component {...props } />;
};

CodePudding user response:

I don't understand why there are two fat arrows

This isn't some special syntax, that's just a arrow function returning another arrow function

// a function taking in a i returning that i
i => i

// a function taking in a i, returning another function which takes in a j and returns i   j
i => j => i   j

above is similar to

function(i) { return i; }

function(i) {
    return function(j) {
        return i   j;
    }
}
  • Related