So I have to class components:
Class1: has a clickbutton
Class2: has a method calling my api
Basically, what I want is to call a method that sets and edits states inside one class from another class. But I keep failing.
Example:
Class1.js
export class Class1 extends Component {
render() {
return (
<div onClick={must call Class2Method}></div>
)
}
}
Class2.js
export class Class2 extends Component {
Class2Method(){
Here I call my API, I set & call states, ...
}
render {
return (
<Class1 />
Here I return my API content
)
}
}
What I tried:
- I have tried to use my method and call and set my states in my App.js (parent of both class2 and class1); but then my Class2.js console says it can't find my states.
- I also tried: < Class1 method={this.Class2Method} /> in my Class 2 and < div onClick={this.props.method} > in Class1.
Here you go
Class1.js
Class2.js
Passdown callApi method to class1 component as a prop and access it in the above component as this.props.callApi and pass it to onClick of div.
First: Consider to use Stateless Functional Components instead of Stateful Components in cases like your "Class1" that don't use states, only props.
Now, to do what you need.. just pass your methods as a prop, something like this:
Using Props
"render prop" refers to a technique for sharing code between React components uising a prop whose value is a function" - reactjs.org
Example
app.js
button.js
Explanation
In
app.js
we imported the component<Button/>
and usingprops
we passed a method fromapp.js
"sayHello
" to a prop we created calledwhenClicked
. Inbutton.js
we referencedthis.props.whenClicked
and passed it to theonClick
property.sayHello
is now being shared between the two components because we passed the method as a prop to the<Button/>
component.