Answer the question
In order to leave comments, you need to log in
How to dynamically add a component in React?
Good afternoon!
Dear experts, please tell me how you can dynamically add a React component?
Let's say there is an onclick event on a component or its descendants. You need to add a new component as a child element to an existing component. appendChild is not suitable because it uses JSX and this function cannot take an object as an argument. That is, you need to essentially describe the appChild function in the example below, or solve it somehow else!
I will be grateful for your help!
import React from 'react';
import ReactDOM from 'react-dom';
import Month from './Month';
import Content from './Content';
function appChild(){
}
ReactDOM.render(
<div>
<Month />
<div onClick='this.appChild.bind(this)'></div>
<Content />
</div>,
document.getElementById('root')
);
Answer the question
In order to leave comments, you need to log in
Make a separate component for this case. No appChild is React.
class MyClickableComponent extends React.PureComponent {
construct(props, context) {
super(props, context)
this.state = {
isOpen: false,
}
}
handleClick = e => {
this.setState({ isOpen: true })
}
render() {
const { isOpen } = this.state
return (
<div>
<div onClick={this.handleClick }>click on me</div>
{isOpen && (
<b>opened!</b>
)}
</div>
)
}
}
ReactDOM.render(
<div>
<Month />
<MyClickableComponent />
<Content />
</div>,
document.getElementById('root')
);
Google immediately gives out the order of questions, but in general, if we are talking about the same type of components, here is a good answer . The essence of it boils down to the fact that you render components based on the data in the state (this could also be the props that came from the parent ..).
(translated the main piece from the answer at the link above)
// ...
// SampleComponent - ваш однотипный компонент
// ...
class Test extends Component {
constructor(props) {
super(props)
this.addChild = this.addChild.bind(this)
this.state = {
components: [
{
id:1, name: 'Some Name'
}
]
}
}
addChild() {
// Изменение стейта спровоцирует перерисовку
this.setState(this.state.concat([
{id:2,name:"Another Name"}
]))
}
render() {
return (
<div>
<h1>App main component! </h1>
<button onClick={this.addChild}>Add component</button>
{ // здесь будет отрисовано необходимое кол-во компонентов
this.state.components.map((item) => (
<SampleComponent key={item.id} name={item.name}/>
))
}
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question