vanegeek
vanegeek

Reputation: 713

Passing data from child to parent in React

Hello I am trying to implement a very simple functionality that would update my state based on the value passed into a function. The function is declared in my parent component, is passed to my child component via props and it is being called on a child component.

I keep getting this error on the console: Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

Here is my code: Parent component

import React, {Component } from "react";
import Sidebar from './Sidebar';
import Content from './Content';

class Tabs extends Component {
    constructor(props){
        super(props);
        this.state={
            message:'Select a name from the tabs menu'

        };
        this.handleName = this.handleName.bind(this);
    }

    componentWillMount () {
        if ('pluginLoaded' in window) {
            (window).pluginLoaded('tabs', function (port: any, context: any) {
                // Future work should interact with the message channel here
            });
        }
    }

    handleName(value){
        if (value === 'Vanessa'){
            console.log(`${value} in da house `)
            this.setState({
                message: 'Vanessa means "butterfly"'
            })
        }


    }

    render() {
        return (
            <div className="Tabs">
                <Sidebar 
                    handleName = {this.handleName}
                />
                <Content
                    message = {this.state.message}
                />


            </div>
        )
    }
}

export default Tabs;

Child component

import React from 'react';

const Sidebar = (props) =>{
    let Vanessa= 'Vanessa';
    let Paola = 'Paola';

    return(
        <div className="Sidebar">
            <h1>Tabs</h1>
            <ul>
                <li><a onClick={props.handleName(Vanessa)}>Vanessa</a></li>
                <li><a onClick={props.handleName(Paola)}>Paola</a></li>
            </ul>
        </div>
    )
}


export default Sidebar;

Upvotes: 0

Views: 2156

Answers (1)

Chanzi
Chanzi

Reputation: 81

Instead of:

<li><a onClick={props.handleName(Vanessa)}>Vanessa</a></li>

try:

<li><a onClick={() => props.handleName(Vanessa)}>Vanessa</a></li>

Upvotes: 5

Related Questions