Pass Argument to Function Reactjs

2698 views javascript
10

I am building a tab bar using react-mdl library. I have an activeTab property in my state object to determine which tab was clicked and render the right information.

I have used an onChange method on the tabs holder to fetch the tab id from user click events and passed the id to my function where the activeTab property will be set from events.

This is what I have done so far:

import React, { Component } from 'react';
import { Tabs, Tab } from 'react-mdl';
import './index.css';

class Projects extends Component {

constructor(props){
    super(props);

    this.state = {
        activeTab: 0
    }

}

handleTabChange(tabId){
    this.setState({
        activeTab: tabId
    });
    console.log(this.state);
}

render() {
    return (
        <div className="">
            <Tabs
                activeTab={this.state.activeTab}
                onChange={ () => this.handleTabChange(tabId)}>
                <Tab>Android</Tab>
                <Tab>Web</Tab>
                <Tab>Full Stack</Tab>
            </Tabs>
        </div>
    );
}

}

export default Projects;

but when I build the project it crashes in browser with this error:

./src/components/Projects/Projects.js
Line 28:  'tabId' is not defined  no-undef

Search for the keywords to learn more about each error.

How can I fix this? Thank you.

answered question

as the error says tabId is an undefined variable. where did you declare it inside the render method?

1 Answer

8

You are almost there. From the react-mdl examples:

You need to pass the tabId as a parameter to the onChange binding.

onChange={ (tabId) => this.handleTabChange(tabId)}

Full example:

<div className="demo-tabs">
                <Tabs activeTab={this.state.activeTab} onChange={(tabId) => this.setState({ activeTab: tabId })} ripple>
                    <Tab>Starks</Tab>
                    <Tab>Lannisters</Tab>
                    <Tab>Targaryens</Tab>
                </Tabs>
                <section>
                    <div className="content">Content for the tab: {this.state.activeTab}</div>
                </section>
            </div>    

posted this

Have an answer?

JD

Please login first before posting an answer.