Call parent component method from child component in react

I’m fairly new to React.There is a problem when I map my child component , DatePicker shows same results in onChange function. Thanks for your help in advance

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            startDate: new Date(),
            options: [1,2,3,4,5,6,7,8,9,10],
            countValue: '',
            showMessage:false,
            persons:[],
        }
        this.someMethod=this.someMethod.bind(this)
    };

    someMethod(date) {
        this.setState({
            startDate: date
        });
        console.log('bar');
    }

    PersonsCount (event) {
        let arr = [];
        for (let i=1;i<=event.target.value;i++) {
            arr.push(
                {id:i,birthDate:'',skiPrice: 0, rentDays: 0, sale: 0}
            )
        }

        this.setState({
            persons: arr , showMessage: !this.state.showMessage, countValue: event.target.value
        })
    };

    render() {
        const {options,showMessage} =this.state;
        return (

            <div>
                <span>Number of people : </span>
                <select onChange={this.PersonsCount.bind(this)}>
                    {
                        options.map(item => {
                            return (<option value={item} key={item}>{item}</option>)
                        })
                    }
                </select>
                {
                    (showMessage) ? <p>Choose birthday date</p> : null
                }
                <ol>
                    {
                        this.state.persons
                            .map((item, index) =>
                                <li key={item.id}>
                                    <Age value={this.state.startDate} parentMethod={this.someMethod} key={item.id}
                                         index={index} >{this.props.children}</Age>
                                </li>
                            )
                    }
                </ol>

            </div>

        )
    }
}


class Age extends Component {
    constructor(props) {
        super(props);

    };

    click = (date) => {
        this.props.parentMethod(date);
    };

    render() {

        return (
            <DatePicker
                selected={this.props.value}
                onChange={this.click}
                peekNextMonth
                showMonthDropdown
                showYearDropdowncd
                dropdownMode="select"
            />
        )
    }
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

Please use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks are not single quotes.

markdown_Forums

1 Like

Thanks for editing…

Do you have a repo or pen for this somewhere? Or at least let us know what package you are using for DataPicker.

I have used https://www.npmjs.com/package/react-datepicker this package

Welcome, Abdullayeva.

I may be wrong, but are you not just forgetting to bind this to your child’s click method?

Specifically, you might want to not use an arrow function, as this is slightly more unpredictable.

I wouldn’t expect it to need it because it is an arrow function.

If you’re referring to this:

 click = date => this.props.parentMethod(date);

Then that is what I would expect to see. That is the ES6 way of doing it, making binding unnecessary.

What about setting up something like a closure for it:

onChange={(e) => this.click(e)}

I’m having a hard time understanding what you want here. I also can’t get the code to work. I created a pen to work on it but all I get is the selector. I never see a date picker - I just get his error in the console:

react-datepicker.min.js:1 Uncaught TypeError: se is not a function
at react-datepicker.min.js:1
at react-datepicker.min.js:1
at react-datepicker.min.js:1

But

onChange={(e) => this.click(e)}

and

onChange={ this.click }

Are functionally equivalent in React. Actually, the second is slightly better because it will not create a new anonymous function on each render, afaik,

1 Like

I added it to my code but nothing changed:(

I use this online editor . You can see it here https://repl.it/repls/OpenRedMouse#src/Age/Age.js

OK, I guess I’m confused by:

DatePicker shows same results in onChange function.

Do you mean, “Why when I change a date does it change all the dates instead of just one?”

That’s because you have only one date. You have one instance of App and that has one state variable that is a single date:

    this.state = {
      startDate: new Date(),

Then your callback for your DatePicker sets that one date:

  someMethod(date) {
    this.setState({
      startDate: date
    });
    console.log("bar");
  }

Then you feed that one date back into all your Age components:

              <Age
                value={this.state.startDate}
                parentMethod={this.someMethod}
                key={item.id}
                index={index}
              >

Perhaps you should consider having an array of dates.

1 Like