Referring to a Component Instance
When a component is render
‘ed’, a React component instance is created from the passed configuration options. One can gain access to this instance and it’s properties (e.g., this.props
) and methods (e.g., this.setState()
) in two ways.
The first way is by using the this
keyword from within a configuration function option. In the code example below all of the console.log(this)
statements will refer to the component instance.
The other way to gain a reference to a component instance involves making use of the return value from calling ReactDOM.render()
. In other words, the ReactDOM.render()
function will return a reference to the top most rendered component.
Notes
- The
this
keyword will commonly be used from within a component to access instance properties likethis.props.[NAME OF PROP]
,this.props.children
, andthis.state
,. It will also be used to call class methods/properties, that all components share likethis.setState
andthis.replaceState()
.