React: Render Certain Element Based On Certain Button Click
Hi I have a react app where I am returning several buttons. What I am trying to do is depending on the button you click another component will show and render in the view. I've loo
Solution 1:
Checkout the code below. I have added another state variable 'view' which gets the name of the view from the button being clicked and in the render checks the state value for which component to render
class FormContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
dropdownVisible: false,
view : ''
};
}
handleClick = view => event => {
if (!this.state.dropdownVisible) {
document.addEventListener('click', this.handleOutsideClick, false);
} else {
document.removeEventListener('click', this.handleOutsideClick, false);
}
this.setState(prevState => ({
dropdownVisible: !prevState.dropdownVisible,
view
}));
}
render() {
return (
<form className="form-container">
<h2>Browse The Database</h2>
<button className="btn btn-default" onClick={this.handleClick('view1')}>
By Fiscal Year
</button>
<button className="btn btn-default" onClick={this.handleClick('view2')}>
By Research Organization
</button>
<div className="table-container">
{this.state.view === 'view1' && <ResearchOrganizationTable />}
</div>
</form>
);
}
}
export default FormContainer;
Solution 2:
try a switch statement.
getView(view) {
switch(view) {
case: view1
return ResearchOrganizationTable />
so each button could have an onClick event that passes the view you want to getView.
Solution 3:
What others suggested, is how I have done it before as well, switch statement, setting state based off button ID. Is this what your looking for:
import React, { Component } from 'react'
const ViewA = () => {
return( <div>A VIEW</div>)
};
const ViewB = () => {
return( <div>B VIEW</div>)
};
const ViewC = () => {
return( <div>C VIEW</div>)
};
const ViewD = () => {
return( <div>D VIEW</div>)
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
view: "A"
};
this.changeView=this.changeView.bind(this);
}
changeView(e){
console.log(e.target.id);
this.setState({
view: e.target.id
})
}
renderButtons(){
return (
<div>
<button id="A" onClick={this.changeView}>RENDER A</button>
<button id="B" onClick={this.changeView}>RENDER B</button>
<button id="C" onClick={this.changeView}>RENDER C</button>
<button id="D" onClick={this.changeView}>RENDER D</button>
</div>
);
}
render() {
const {view} = this.state;
switch(view) {
case "A":
return(
<div>
{this.renderButtons()}
<ViewA/>
</div>
)
case "B":
return(
<div>
{this.renderButtons()}
<ViewB/>
</div>
)
case "C":
return(
<div>
{this.renderButtons()}
<ViewC/>
</div>
)
case "D":
return(
<div>
{this.renderButtons()}
<ViewD/>
</div>
)
}
}
}
export default App;
Post a Comment for "React: Render Certain Element Based On Certain Button Click"