I would like to know how I can destroy a component with React when I click a button. I found a way out, but in my design it is very "gambiarrosa". I have a state called show
and when I click close I modify the value of this.state.show
to false, in the render () method I use an if ternary to render the component or not depending on the this.state.show
value.
MyComponent.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import FontAwesome from 'react-fontawesome';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
show:true,
};
}
closeComponent(){
console.log("Destruir componente");
var x = ReactDOM.findDOMNode(this);
console.log(x);
//ReactDOM.unmountComponentAtNode(this.container);
this.setState({ show: false });
}
componentDidMount() {
}
componentWillUnmount() {
clearInterval(this.state);
}
render() {
return (
this.state.show ?
<div className="MyComponent">
<h1>Mostrar componente</h1>
<FontAwesome name="window-close-o" onClick={this.closeComponent.bind(this)}/>
</div>
: null
);
}
}
export default MyComponent;
Is this really the only pro-output I need to do?
ComponentFather.js
import React, { Component } from 'react';
import './ComponentFather.css';
import MyComponent from '../MyComponent/MyComponent'
class ComponentFather extends Component {
constructor(props) {
super(props);
this.state = {
value: "Adicionar Categoria",
key: 0,
matchs: [],
};
}
componentDidMount(){
}
componentWillUnmount(){
clearInterval(this.state);
}
buttonClicked(){
var mat = this.state.matchs;
this.state.key ++;
mat.push(<Match key={this.state.key}/>);
console.log(mat);
this.setState({
matchs: mat
});
}
render() {
return (
<div className="ComponentFather">
<h1>Events Information</h1>
<MyComponent></MyComponent>
<MyComponent></MyComponent>
<MyComponent></MyComponent>
</div>
);
}
}
export default ComponentFather;
MainComponent
import React, { Component } from 'react';
//import logo from './logo.svg';
import './App.css';
import ComponentFather from '../ComponentFather/ComponentFather';
import Streaming from '../Streaming/Streaming';
//import {Grid, Row, Col, Clearfix} from 'react-bootstrap';
class App extends Component {
render() {
return (
<div className="App">
<ComponentFather />
<Streaming />
</div>
);
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/App';
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/css/bootstrap-theme.css'
ReactDOM.render(
<App />,
document.getElementById('main-container')
);