Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the second parameter for in a React functional component?

Tags:

reactjs

I noticed in a React.js functional component like:

import React from 'react';
import ReactDOM from 'react-dom';

function MyComponent(props, whatIsThisFor) {
  console.log(JSON.stringify(whatIsThisFor)); // logs {} to console
  return <div></div>
}

ReactDOM.render(<MyComponent />, document.getElementById('root'));

The whatIsThisFor parameter gets set to an empty object when it is rendered. I could not find the purpose of this parameter in any documentation. Does anyone know what it is for?

like image 533
ken_o Avatar asked Jul 03 '19 23:07

ken_o


1 Answers

As you investigated, the second param is reference forwarded using React.forwardRef(…) API. In docs - Forwarding refs to DOM components - you can find more info about the topic.

Edit:

This comment with this link, tells that I was only partially correct - regarding refs.

The second parameter in linked code is called refOrContext. It means, the parameter may be also a context and it seems to be a part of the Legacy Context API.

Caution: do not use Legacy Context API; use new Context API instead.

In short, when you define contextTypes field in a functional component, you'll receive an object with the defined shape as a second parameter. If the component is nested under another class component that implements getChildContext and returns object with some fields, these fields are available in context only when you mark them in contextTypes. Here's an example of the component:

import PropTypes from 'prop-types';

const ContextConsumer = (props, context) => {
  console.log(context); // { name: … }
  return …;
};

ContextConsumer.contextTypes = {
  name: PropTypes.string,
  …
};

export default ContextConsumer;

The complete example can be found on my StackBlitz. For more information, please read about Legacy context API.

like image 188
pawel-schmidt Avatar answered Oct 20 '22 01:10

pawel-schmidt