I want to render a component when i clicked a button to do this I added a state to remember click .There a four different buttons which render four different components do I have to add state for each and every button ? is there another way to do this?
Asked
Active
Viewed 467 times
0
-
Can you include your code in your question? Edit your post and paste the code in. – Chris Jul 10 '17 at 08:57
-
this question is similar to https://stackoverflow.com/questions/43714596/is-there-a-neater-way-to-connect-an-input-field-to-a-state-property-in-react-tha/43714677#43714677 and https://stackoverflow.com/questions/43671680/use-a-single-handler-for-multiple-inputs-onchange-events/43671789#43671789 – Shubham Khatri Jul 10 '17 at 09:03
-
Welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour), have a look around, and read through the [help center](https://stackoverflow.com/help) , in particular [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [What topics can I ask about here?](https://stackoverflow.com/help/on-topic). – Yagami Light Jul 10 '17 at 09:10
2 Answers
0
You should have a parent component. In this parent component should be all the child components you want to show when you click the button. Then in the parent component, you have a state property (e.g. activePage), then you set it to a string representating the page name (e.g. activePage="page1").
In your parents render function, you can now create a switch statement, which checks which component it should render (return).
I think this would be a more clean approach than setting the state on the child elements.

Larce
- 841
- 8
- 17
-
-
Of course you can add multiple components - just extend the switch statement. – Larce Jul 10 '17 at 09:01
0
yes you can do it.Say for each button you have 4 functions defined
a:function()
{
this.setState({
flag:a,
value:"hii"
})
}
b:function()
{
this.setState({
flag:b
})
}
c:function()
{
this.setState({
flag:c
})
}
d:function()
{
this.setState({
flag:d
})
}
now you can send this state as props to your 4 components as
<button onClick="this.a"/>
<button onClick="this.b"/>
<button onClick="this.c"/>
<button onClick="this.d"/>
and in render you can call components like render{
if(this.state.flag==='a')
return <ComponentA finalstate={this.state.value}/>
....follow if else control structure
}

Vikram Saini
- 2,713
- 1
- 16
- 33