0
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      activeTab: "add",
      items: [],
    }
  }
  handleClick(activeTab) {
    switch (activeTab) {
      case 'add': return <Add/>
      case 'list': return <List />
      case 'pay': return <Pay />
    }
  }
  render() {
    return (
      <div className="App btn-group">
        <Button onClick={this.handleClick.bind(this, 'add')}><Add /></Button>
        <Button onClick={this.handleClick.bind(this, 'list')}><List /></Button>
        <Button onClick={this.handleClick.bind(this, 'pay')}><Pay /></Button>
      </div>
    )
  }
}
export default App;

I wish through this code in reactjs, When I onClick on an 'add' button it shows me the Add components but unfortunately it does not work. On the other hand in my switch when I do an alert () or a console.log () instead of returning my components; it works well as it should.

the <Add /> List and Pay are components and I have imported into the app.js.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
lydy
  • 3
  • 2

1 Answers1

1

there are several issues with your code.

  1. if you want to show the components based on your active Tab you have to maintain the state variable . I see you have set your initial state activeTab : "add" but trying to render <Add /> component inside a button . that's why it doesn't work as expected . you have to render it separately .

  2. your handleClick function is supposed to do something . not return something. so here if you return your components inside switch that won't work. you can change the state here.

  3. you can use the conditional rendering feature of react to render the desired component based on your active tab as shown below.

here is the complete component code that should solve the problems i mentioned above

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      activeTab: "add",
      items: [],
    }
  }

  handleClick(activeTab) {
    this.setState({activeTab})
  }

  render() {
    return (
      <div>

 
        <div className="App btn-group">
            <Button onClick={this.handleClick.bind(this, 'add')}> Add </Button> 
            <Button onClick={this.handleClick.bind(this, 'list')}> List </Button>
            <Button onClick={this.handleClick.bind(this, 'pay')}> Pay </Button>  
        </div>

        {this.state.activeTab === 'add' &&  <Add /> }
        {this.state.activeTab === 'list' &&  <List /> }
        {this.state.activeTab === 'pay' &&  <Pay /> }
      </div>
    )
  }
}
export default App;
Mohammad Faisal
  • 2,265
  • 1
  • 10
  • 16