Reputation: 491
I want a component with a alert function to be activated when clicking on a button in a class-component.
import React from 'react'
export default function ConfirmationModal() {
alert = () => {
alert("whatsup hotdawg?")
}
return (
<div>
{this.alert()}
</div>
)
}
i have this line that i would like to trigger the Alert method in the functional component onClick
<button>"ClickMe" onClick=<ConfirmationModal/> </button>
Any suggestions on how i can perform this would be much appreciated.
Upvotes: 1
Views: 83
Reputation: 817
React is Component based library, So add your ui component(button) and associated logic in the same component.
Change your functional Component to following.
import React from 'react';
export default class ConfirmationModal extends React.Component {
alert = () => {
alert("whatsup hotdawg?")
}
render () {
return (
<button onClick={this.alert}>"ClickMe"</button>
)
}
}
And in your class component import the above component and use it. Your Class Component should look something like this.
render(){
return (
<ConfirmationModal />
)
}
Upvotes: 1
Reputation: 112777
You could keep a piece of state in your parent component called e.g. isModalOpen
that you set to true when clicking the button, and use this piece of state to conditionally render the ConfirmationModal
.
It's also a good idea to not call methods directly on render, since that will occur on every render. You can move the alert to componentDidMount
instead.
Example
class ConfirmationModal extends React.Component {
componentDidMount() {
alert("whatsup hotdawg?");
}
render() {
return <div>Modal</div>;
}
}
class App extends React.Component {
state = {
isModalOpen: false
};
render() {
return (
<div>
<button onClick={() => this.setState({ isModalOpen: true })}>
Click me
</button>
{this.state.isModalOpen && <ConfirmationModal />}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 3