Call a React component inside a function, when a button is clicked
13,972
Solution 1
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;
Solution 2
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.
Author by
srinivas
Updated on June 13, 2022Comments
-
srinivas almost 2 years
The
Container
component is not getting rendered. Can anyone guide me why I'm not able to render theContainer
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>; } }
-
srinivas almost 6 yearsyour solution is not solved my problem, I want to call component inside a function. @Shubham Khatri
-
Shubham Khatri almost 6 yearswhat do you mean by calling the component? From what I understand its simply rendering it which is possible withthe above methods