I have a react ponent which I want to self close when I click a button that's on the ponent itself.
Here's the code:
import React from 'react';
import PropTypes from 'prop-types';
const MyReactComponent = (props) => <div>
<h1>TEST</h1>
<button onClick={self close here?}>Self Close</button>
</div>
export default MyReactComponent
How can I get the button click to close the ponent when I click it?
I have a react ponent which I want to self close when I click a button that's on the ponent itself.
Here's the code:
import React from 'react';
import PropTypes from 'prop-types';
const MyReactComponent = (props) => <div>
<h1>TEST</h1>
<button onClick={self close here?}>Self Close</button>
</div>
export default MyReactComponent
How can I get the button click to close the ponent when I click it?
Share Improve this question asked Oct 3, 2018 at 8:10 user10450072user10450072 01 Answer
Reset to default 13That's not how React works. :-) Instead, the parent of the ponent should pass it a property that it uses as the onClick
. In response to the click, the parent ponent changes its state so that the child is no longer rendered:
const MyReactComponent = (props) => <div>
<h1>TEST</h1>
<button onClick={props.onClose}>Self Close</button>
</div>;
class ParentComponent extends React.Component {
// Note: This uses the class fields proposal, currently at Stage 3 and
// monly transpiled in React projects
closeChild = () => {
this.setState({
showChild: false
});
};
constructor(...args) {
super(...args);
this.state = {
showChild: true
};
}
render() {
return (
<div>
{this.state.showChild && <MyReactComponent onClose={this.closeChild} />}
</div>
);
}
}
ReactDOM.render(
<ParentComponent />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
More in the "Lifting State Up" part of the documentation.