Why can’t I access the component methods from “outside” in ReactJS? Why is it not possible and is there any way to solve it?
Consider the code:
var Parent = React.createClass({ render: function() { var child = <Child />; return ( <div> {child.someMethod()} // expect "bar", got a "not a function" error. </div> ); } }); var Child = React.createClass({ render: function() { return ( <div> foo </div> ); }, someMethod: function() { return 'bar'; } }); React.renderComponent(<Parent />, document.body);
To access a React context outside of the render function, we can use the useContext hook. We create the UserContext by calling the React. createContext method with a default context value. Then in the Users component, we call the useContext hook with UserContext to accxess the current value of UserContext .
In React, the onClick handler allows you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app. Click on any of the examples below to see code snippets and common uses: Call a Function After Clicking a Button.
The child component uses the props argument to know what to render. Now, we can pass a function to the props object. You see we passed a function () => [ "nnamdi", "chidume" ] to ChildComponent via name ,then it can access it by referencing it as key in the props argument: this.props.name .
React provides an interface for what you are trying to do via the ref
attribute. Assign a component a ref
, and its current
attribute will be your custom component:
class Parent extends React.Class { constructor(props) { this._child = React.createRef(); } componentDidMount() { console.log(this._child.current.someMethod()); // Prints 'bar' } render() { return ( <div> <Child ref={this._child} /> </div> ); } }
Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component
Update 2019-04-01: Changed example to use a class and createRef
per latest React docs.
Update 2016-09-19: Changed example to use ref callback per guidance from the ref
String attribute docs.
If you want to call functions on components from outside React, you can call them on the return value of renderComponent:
var Child = React.createClass({…}); var myChild = React.renderComponent(Child); myChild.someMethod();
The only way to get a handle to a React Component instance outside of React is by storing the return value of React.renderComponent. Source.
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