The Container
component is not getting rendered. Can anyone guide me why I'm not able to render the Container
component?
App.js
import React, { Component } from "react";
import "./App.css";
import Container from "./Container";
class App extends Component {
add() {
return <Container />;
}
render() {
return (
<div className="App">
<button onClick={() => this.add()}>CLICK</button>
</div>
);
}
}
export default App;
Container.js
import React, { Component } from "react";
export default class Container extends Component {
render() {
return <h1>hello</h1>;
}
}
You can set a state and render the component on button click
import React, { Component } from "react";
import "./App.css";
import Container from "./Container";
class App extends Component {
state = {
addContainer: []
}
add() {
this.setState(prevState => {addContainer: prevstate.addContainer.concat([0])})
}
render() {
return (
<div className="App">
{this.state.addContainer.map(() => {
return <Container />
})}
<button onClick={() => this.add()}>CLICK</button>
</div>
);
}
}
export default App;
or if its just a single container whose visibility you want to toggle on button click
import React, { Component } from "react";
import "./App.css";
import Container from "./Container";
class App extends Component {
state = {
addContainer: false
}
add() {
this.setState(prevState => {addContainer: !prevstate.addContainer)})
}
render() {
return (
<div className="App">
{this.state.addContainer && <Container />}
<button onClick={() => this.add()}>CLICK</button>
</div>
);
}
}
export default App;
Your function isn't rendering because the return of your method add()
isn't inside your render()
method. It's inside the onClick()
, so it won't render. Try like the snippet bellow:
class Container extends React.Component {
render(){
return <h1> Hello World </h1>
}
}
class App extends React.Component {
state= { render: false }
add = () => {
this.setState({render : !this.state.render})
}
render() {
return (
<div className="App">
<button onClick={() => this.add()}>CLICK</button>
{ this.state.render &&
<Container/>
}
</div>
);
}
}
ReactDOM.render(<App/>,document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You can even toggle the <Container>
rendering, as I did above, but you can't return a Component inside a onClick and expect that it'll be rendered.
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