React function with parameters inside Component/Element

Viewed 130

I just used a library called react-axios where a function is supplied inside of a component in the following way:

<Get url="/api/user" params={{id: "12345"}}>
{(parameters) => {
 //some callback with the parameters
}}
</Get>

As I have never seen this syntax before and always passed functions with props, I am curious:

  • How is this type of function-specification called in React?
  • How can a Component be implemented like this?
  • Does it also work with function-components?
1 Answers
  • How is this type of function-specification called in React?

The pattern that you suggest in your questions is called render props pattern

  • How can a Component be implemented like this?

A very basic implementation can be somethinng like below

    function Get(props) {
       const [params, setParams] = useState({}); 
       ...
       return (
        <div>{props.children(params)}</div>
       )
    }
  • Does it also work with function-components?

Yes it can be writen for functional components as well as class components

Related