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?
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 ref
s.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With