0

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>
);
Christopher Vickers
  • 1,773
  • 1
  • 14
  • 18
  • This is a render prop technique where you share code between components using props whose value is a function. [Read More](https://reactjs.org/docs/render-props.html) – humanbean May 06 '19 at 19:33
  • Thank you but I dont mean the value inside the div eg ref={ref}. I'm familiar with that part. I mean this part: ({ ref, style, placement, arrowProps }). Surely the code should be this.props.ref ? – Christopher Vickers May 06 '19 at 19:38
  • Go through the docs, which I have mentioned in my first comment. `And remember, the children prop doesn’t actually need to be named in the list of “attributes” in your JSX element. Instead, you can put it directly inside the element!` Once you reach this line it should be clear. – humanbean May 06 '19 at 19:45

2 Answers2

1

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.

Kyle Willmon
  • 709
  • 3
  • 13
0

They are render props for the Popper component. They are all parameters of the render prop function defined in the Popper file you can find on the GitHub for this package. I'm not familiar with this specific library, but basically they are being passed to that function, and they need to be there as it's defined or it will throw an error. You should be able to compute your own values for styles and whatnot but again I'm not familiar with this package.

Chris B.
  • 5,477
  • 1
  • 12
  • 30