I want to return a component <SaveTask/> to a div tag where <div id="saveTask">. I tried to use this.setState(), but it changes the container and displays the <SaveTask/> component. I want to keep that container and under that container, I want to append a component after clicking a button. Is there any way to add component using document.getElementById('saveTask').
import React, { Component } from 'react'
import SaveTask from './SaveTask';
export default class TaskHeader extends Component {
constructor(props) {
super(props)
this.state = {
saveTask: false,
}
this.showComp = () => {
this.setState({
saveTask: true,
})
}
}
render() {
if(this.state.saveTask) {
return (
document.getElementById('saveTask').innerHTML = <SaveTask/>
)
}
return (
<div>
<div className="container-fluid bg-white border-bottom">
<div className="row">
<div className="col-12">
<div className="tasks-upper text-muted">TASK MANAGEMENT APP</div>
<div className="tasks-lower">
<span className="text-secondary text-size">TASK</span><button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>
</div>
</div>
</div>
</div>
<div id="saveTask">
Return a component to this section when clicking the button
</div>
</div>
)
}
}
>Solution :
Yeah, so the beauty of react is that you don’t need to and shouldn’t be updating the innerhtml to update a component. You can simply use a ternary to determine what component to show later on:
import React, { Component } from 'react'
import SaveTask from './SaveTask';
export default class TaskHeader extends Component {
constructor(props) {
super(props)
this.state = {
saveTask: false,
}
this.showComp = () => {
this.setState({
saveTask: true,
})
}
}
render() {
return (
<div>
<div className="container-fluid bg-white border-bottom">
<div className="row">
<div className="col-12">
<div className="tasks-upper text-muted">TASK MANAGEMENT APP</div>
<div className="tasks-lower">
<span className="text-secondary text-size">TASK</span><button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>
</div>
</div>
</div>
</div>
{this.state.saveTask ? (
<SaveTask/>
) : (
<div id="saveTask">
Return a component to this section when clicking the button
</div>
)}
</div>
)
}
}
In this case you’re saying, "if this.state.saveTask is true, then show <SaveTask /> otherwise, show the <div id="saveTask"> element. If you wanted inside that div, then you would just move the ternary inside it.
