react.js call parent function from child

Joelio

I know there are a few similar questions here and here but I am having a tough time understanding what is the correct thinking today on this and extrapolating it to my situation.

I have a simple app, ScoreBox has a ScoreList which has many Scores. I want to have a Score onClick call ScoreList handleScoreRemove. I am showing the full js file, but the most important lines are line 5 and line 77.

var Score = React.createClass({
  removeRecord: function(e){
      // How do I do this?
      ScoreList.handleScoreRemove(e);
  },
  render: function() {
    var team1_style = (this.props.team1_score >= this.props.team2_score) ?
        {fontWeight: 'bold'} : {};
    var team2_style = (this.props.team2_score >= this.props.team1_score) ?
            {fontWeight: 'bold'} : {};
        return (
            <tr>
              <td style={team1_style}>{this.props.team1_name}:</td><td style={team1_style}>{this.props.team1_score}</td>
              <td style={team2_style}>{this.props.team2_name}:</td><td style={team2_style}>{this.props.team2_score}</td>
              <td><a hef="#" id={this.props.id} onClick={this.removeRecord}>remove</a></td>
            </tr>
    );
  }
});

var ScoreBox = React.createClass({
  loadScoresFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  handleScoreSubmit: function(score) {
    var scores = this.state.data;
    // Optimistically set an id on the new score. It will be replaced by an
    // id generated by the server. In a production application you would likely
    // not use Date.now() for this and would have a more robust system in place.
    score.id = Date.now();
    var newScores = scores.concat([score]);
    this.setState({data: newScores});
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: score,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        this.setState({data: scores});
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadScoresFromServer();
    setInterval(this.loadScoresFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="scoreBox">
        <h1>Scores</h1>
        <ScoreList data={this.state.data} />
        <ScoreForm onScoreSubmit={this.handleScoreSubmit} />
      </div>
    );
  }
});

var ScoreList = React.createClass({
  handleScoreRemove: function(score) {
    var scores = this.state.data;
    var index_of_score = array.indexOf(score);
    var newScores = scores.splice(index_of_score, 1);
    this.setState({data: newScores});
    $.ajax({
      url: this.props.url + "/" + score[id],
      dataType: 'json',
      type: 'DELETE',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        this.setState({data: scores});
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    var scoreNodes = this.props.data.map(function(score) {
      return (
        <Score key={score.id} id={score.id} team1_name={score.team1_name} team1_score={score.team1_score} team2_name={score.team2_name} team2_score={score.team2_score} >
        </Score>
      );
    });
    return (
      <div className="scoreList">
        <table>
          <tbody>
            {scoreNodes}
          </tbody>
        </table>
      </div>
    );
  }
});

var ScoreForm = React.createClass({
  checkForCompleteForm: function(){
    if (this.state.team1_name.length > 0 && this.state.team2_name.length > 0 && this.state.team1_score.length > 0 && this.state.team2_score.length > 0)
    {
      // enable the button
      $("input[type=submit]").removeAttr('disabled');
    }

  },
  getInitialState: function() {
    return {id: '', team1_name: '', team1_score: '', team2_name: '', team2_score: ''};
  },
 handleChange : function (e) {
    // this is a generic handle change function that uses the html id to set the state instead of
    // having a bunch of if statements
    var stateObject = function() {
      var returnObj = {};
      returnObj[this.target.id] = this.target.value;
      return returnObj;
    }.bind(e)();
    // setState is async which makes this painful
    //  JCN - why when I pass checkForCompleteForm as 2nd param it doesnt work, but instead I need this
    // function bind stuff... need to understand exactly what this is doing
    this.setState( stateObject, function(){
        this.checkForCompleteForm();
    }.bind(this));
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var team1_name = this.state.team1_name.trim();
    var team1_score = this.state.team1_score.trim();
    var team2_name = this.state.team2_name.trim();
    var team2_score = this.state.team2_score.trim();
    if (!team1_name || !team1_score ) {
      return;
    }
    this.props.onScoreSubmit({team1_name: team1_name, team1_score: team1_score,team2_name: team2_name, team2_score: team2_score });
    this.setState({team1_name: '', team1_score: '', team2_name: '', team2_score: ''});
  },
  render: function() {
    return (
      <form className="scoreForm" onSubmit={this.handleSubmit}>
        <input
          id='team1_name'
          type="text"
          placeholder="Team1 Name"
          value={this.state.team1_name}
          onChange={this.handleChange}
        />
        <input
          id='team1_score'
          type="number"
          placeholder="Team1 Score"
          value={this.state.team1_score}
          onChange={this.handleChange}
        />
        <input
          id='team2_name'
          type="text"
          placeholder="Team2 Name"
          value={this.state.team2_name}
          onChange={this.handleChange}
        />
        <input
          id='team2_score'
          type="number"
          placeholder="Team2 Score"
          value={this.state.team2_score}
          onChange={this.handleChange}
        />
        <input type="submit" value="Post" disabled />
      </form>
    );
  }
});

ReactDOM.render(
  <ScoreBox url="/api/scores" pollInterval={2000} />,
  document.getElementById('content')
);
Oleksandr T.

You need to pass handleScoreRemove through props

var scoreNodes = this.props.data.map(function(score) {
  return <Score
    key={score.id}
    id={score.id}
    team1_name={score.team1_name}
    team1_score={score.team1_score}
    team2_name={score.team2_name}
    team2_score={score.team2_score}
    handleScoreRemove={this.handleScoreRemove.bind(this)}>
  </Score>
}, this);

and in Score component call it like this

removeRecord: function(e) {
   this.props.handleScoreRemove( /* add arguments what do you need */ );
},

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

how to call function of child in functional component from parent in react.js?

From Dev

Unable to call parent component function from child component in React

From Dev

How to have a React child component call a function from a parent component

From Dev

How to call parent function from child prop React 15.5.0

From Dev

How to call a parent function from a child - react-native

From Dev

How to call a parent function from the child in react native

From Dev

How to call React/Typescript child component function from parent component?

From Dev

How can I call Child function from Parent Component in React

From Dev

How to call child function from Parent react hook

From Dev

React.js - How to execute function in parent with arguments from child

From Dev

Handling Parent function call in Child in React

From Dev

Call parent function with child data in react native

From Dev

Trigger parent API call from child in react

From Dev

oop call parent function from child class

From Dev

call child function from parent in reactjs

From Dev

Call child component function from parent

From Dev

JavaScript call parent function from child object

From Dev

Angular 11 - Call parent function from child

From Dev

AureliaJS - Call child function from parent

From Dev

Call a parent component function from a child component

From Dev

PHP - Call a parent function from a parent function in a child instance

From Dev

How to fire a function in child from parent in react?

From Dev

How to pass function from parent to a child in react?

From Dev

Call parent's function from child of a child in SwiftUI

From Dev

How to call function of a parent from child and do not update the parent state?

From Dev

How to Call child function from parent component in React Native functional component?

From Dev

Call Child function from Parent React Native - TypeError cannot read property of null

From Dev

How do you call a parent function from a child component (with parameters) in react-native?

From Dev

How to call function in parent class component by onchange event from child component in React?

Related Related

  1. 1

    how to call function of child in functional component from parent in react.js?

  2. 2

    Unable to call parent component function from child component in React

  3. 3

    How to have a React child component call a function from a parent component

  4. 4

    How to call parent function from child prop React 15.5.0

  5. 5

    How to call a parent function from a child - react-native

  6. 6

    How to call a parent function from the child in react native

  7. 7

    How to call React/Typescript child component function from parent component?

  8. 8

    How can I call Child function from Parent Component in React

  9. 9

    How to call child function from Parent react hook

  10. 10

    React.js - How to execute function in parent with arguments from child

  11. 11

    Handling Parent function call in Child in React

  12. 12

    Call parent function with child data in react native

  13. 13

    Trigger parent API call from child in react

  14. 14

    oop call parent function from child class

  15. 15

    call child function from parent in reactjs

  16. 16

    Call child component function from parent

  17. 17

    JavaScript call parent function from child object

  18. 18

    Angular 11 - Call parent function from child

  19. 19

    AureliaJS - Call child function from parent

  20. 20

    Call a parent component function from a child component

  21. 21

    PHP - Call a parent function from a parent function in a child instance

  22. 22

    How to fire a function in child from parent in react?

  23. 23

    How to pass function from parent to a child in react?

  24. 24

    Call parent's function from child of a child in SwiftUI

  25. 25

    How to call function of a parent from child and do not update the parent state?

  26. 26

    How to Call child function from parent component in React Native functional component?

  27. 27

    Call Child function from Parent React Native - TypeError cannot read property of null

  28. 28

    How do you call a parent function from a child component (with parameters) in react-native?

  29. 29

    How to call function in parent class component by onchange event from child component in React?

HotTag

Archive