Wasteland Wasteland - 1 month ago 15
React JSX Question

Reactjs - method giving error

I'm trying to display a component depending on which button gets clicked but have problems with this line.

{this.showTab({this.state.active})}


It throws an error about syntax error. What am I doing wrong and is there a better way of displaying one of the components
<Grids />
,
<Pics />
or
<Maths />
depending on what I click.

import React, {Component} from 'react';
import Pics from './pics';
import Grids from './grids';
import Maths from './maths';
import { ButtonToolbar } from 'react-bootstrap';
import { Button } from 'react-bootstrap';



export default class Tabs extends Component {
constructor(props) {
super();
this.state = {
count: 0,
active: null
};
this.handleClick = this.handleClick.bind(this);
this.showTab = this.showTab.bind(this);
}

handleClick(value) {
this.setState({
count: this.state.count + 1,
active: value
});
}

showTab(tab) {
switch(tab) {
case "Grids":
return "<Grids />";
break;
case "Pics":
return "<Pics />";
break;
default:
return "<Maths />";
}
}

render() {
return (
<div>
<ButtonToolbar>
{this.props.tabs.map(listValue =>
<Button onClick={this.handleClick.bind(this, listValue)}>
{listValue}
</Button>
)}
</ButtonToolbar>

{this.showTab({this.state.active})}



</div>
);
}
}

Answer

This is what you want:

import React, {Component} from 'react';
import Pics from './pics';
import Grids from './grids';
import Maths from './maths';
import { ButtonToolbar } from 'react-bootstrap';
import { Button } from 'react-bootstrap';

export default class Tabs extends Component {
  constructor() {
    super();
    this.state = {
      count: 0,
      active: null
    };
    this.handleClick = this.handleClick.bind(this);
    this.showTab = this.showTab.bind(this);
  }

  handleClick(value) {
    this.setState({
      count: this.state.count + 1,
      active: value
    });
  }

  showTab(tab) {
    switch (tab) {
      case 'Grids':
        return <Grids />;
      case 'Pics':
        return <Pics />;
      default:
        return <Maths />;
    }
  }

  render() {
    const { tabs } = this.props;
    const { active } = this.state;
    return (
      <div>
        <ButtonToolbar>
          {tabs.map(listValue =>
            <Button onClick={() => this.handleClick(listValue)}>
              {listValue}
            </Button>
          )}
        </ButtonToolbar>
        {this.showTab(active)}
      </div>
    );
  }
}

Note how the destructuring assignment can keep your component easy to read. example const { tabs } = this.props; note that I use single quotes instead of "" components markup doesn't need quotes. See how we use arrow function onClick. as you already binded the onClick in the constructor don't bind it again on the actual click... Hope my example helped you

Comments