Search code examples
reactjsreact-popper

React (not sure where a variable comes from)


I am new to React and am trying to understand React-Popper. This is some code from

https://www.npmjs.com/package/react-popper

Where are the values for 'ref', 'style', 'placement' and 'arrowProps' coming from and how would I edit them? I understand that you can use this.props and attributes to pass values to Components but i dont understand where the values to be inserted into the function is coming from.

import { Manager, Reference, Popper } from 'react-popper';

const Example = () => (
  <Manager>
    <Reference>
      {({ ref }) => (
        <button type="button" ref={ref}>
          Reference element
        </button>
      )}
    </Reference>
    <Popper placement="right">
      {({ ref, style, placement, arrowProps }) => (
        <div ref={ref} style={style} data-placement={placement}>
          Popper element
          <div ref={arrowProps.ref} style={arrowProps.style} />
        </div>
      )}
    </Popper>
  </Manager>
);

Solution

  • What you're seeing here is an arrow function being combined with destructuring assignment and React Render Props. So it's a lot in one code example.

    From your question, I think what's confusing you most is the destructuring assignment. So here is an example which I hope will help you:

    var foo = ({a, b}) => a + b;
    
    var x = {
      a: 1,
      b: 2
    };
    
    console.log(foo(x));
    # Output is 3
    

    This is because destructuring assignment assigns the values from the object into the variables a and b as if they were function parameters. The same thing is happening with the props object on the React components and that's why you don't see props.ref, etc.