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.
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
)
}
}
Each React application consists of several components, and each component may require user interaction that triggers various actions. To achieve user interactivity, we can call functions and methods to accomplish specific operations in React.
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.
Here you go
Class1.js
export class Class1 extends Component {
render() {
return (
<div onClick={this.props.callApi}></div>
)
}
}
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.
export class Class2 extends Component {
callApi = () => {
Here I call my API, I set & call states, ...
}
render {
return (
<Class1 callApi={this.callApi} />
Here I return my API content
)
}
}
How do i call a method from another class component in react.js
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
import Button from '../../pathtoButton';
export class App extents Component {
constructor(props){
super(props)
this.state = {
name:'John'
}
}
sayHello(){
const { name } = this.message;
alert(`Hello ${name}`}
}
render(){
return (
<div>
<Button
value="click me"
whenClicked={this.sayHello}
</div>
);
}
}
button.js
export class Button extents Component {
constructor(props){
super(props)
this.state = {
style:{background:'red', color:'white'},
}
}
render(){
const { style } = this.state;
const { whenClicked, value} = this.props;
return (
<div>
<button style={style} onClick={whenClicked}>{value}</button>
</div>
);
}
}
Explanation
In app.js
we imported the component <Button/>
and using props
we passed a method from app.js
"sayHello
" to a prop we created called whenClicked
. In button.js
we referenced this.props.whenClicked
and passed it to the onClick
property.
sayHello
is now being shared between the two components because we passed the method as a prop to the <Button/>
component.
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