David Johns
David Johns

Reputation: 1714

How to solve the error "this.props.myFunction" is not a function in react?

I have a react app with two components. My child component has a table with some records. Each record has a button and I'm calling a function (editUser) with a parameter (id) in onclick. In that function I'm sending that id to the Parent component through props. The function is already bind in the constructor. But when button click, console says this.props.userId is not a function

Child component :

class UsersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
        this.editUser = this.editUser.bind(this);

    }

    editUser(id) {
       this.props.userId(id);
    }

    render() {
        return (
        <TableBody>
            {data
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map(n => {
                    return (
                        <TableRow key={n.id}>
                            <TableCell className={classes.fixedTd}>
                                <BorderColorIcon onClick={() => this.editUser(n.userId)} className="action margin-r" />
                            </TableCell>
                        </TableRow>
                    );
                })}
        </TableBody>
        );
    }
}

export UsersTable;

Parent component :

class CompanyUserMgt extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    editUser = (id) => {
        console.log("user", id)
    }


    render() {
        return (
            <div className="">
        <UsersTable
            userId={this.editUser}
                    key={this.state.tableKey}
                />
            </div>
        )
    }
}

export default CompanyUserMgt;

How can I solve this?

Upvotes: 2

Views: 945

Answers (1)

Dimitrios Douras
Dimitrios Douras

Reputation: 506

I think you can simplify things, can you plese try below code on your child component?

class UsersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };

    }

    render() {
        return (
        <TableBody>
            {data
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map(n => {
                    return (
                        <TableRow key={n.id}>
                            <TableCell className={classes.fixedTd}>
                                <BorderColorIcon onClick={() => this.props.userId(n.userId)} className="action margin-r" />
                            </TableCell>
                        </TableRow>
                    );
                })}
        </TableBody>
        );
    }
}

export UsersTable;

Upvotes: 1

Related Questions