Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

409
Views
In react - updating an array from child component to a parent component

Im trying to add numbers to an array in the parent from the child component . when i try to send data only based on a random number it seems that the numbers are confused . (the game im trying to bulid is Lights Out)

Parent :

import "./App.css";
import Square from "./Square";
import react, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lightNums: [],
    };
  }
   showNum(n) {
     this.setState((st) => ({
      lightNums: [...st.lightNums, n],
    }));
    
  }
  arr = Array.from({ length: 25 }).map((e, g) => {
    return <Square num={g} key={g} showNum={this.showNum.bind(this)} />;
  });

  render() {
    return <div className="App">{this.arr}</div>;
  }
}

export default App;

And the child :

import react, { Component } from "react";
import "./Square.css";

class Square extends Component {
  constructor(props) {
    super(props);
    this.clickHandler = this.clickHandler.bind(this);
    this.state = {
      clicked: this.rand(this.props.num),
    };
  }

  clickHandler(e) {
    this.props.showNum(this.props.num);
    this.setState((st) => ({ clicked: st.clicked ? false : true }));
  }
   rand = (num) => {
    const rand = Math.floor(Math.random() * 2);
    if (rand === 1) 
    {
      this.props.showNum(num);
      return true;
    } 
    else {
      return false;
    }
  };
  classN = () => `square ${this.state.clicked ? "clicked" : ""}`;

  render() {
    return (
      <div className={this.classN()} onClick={this.clickHandler}>
        {this.props.num}
      </div>
    );
  }
}

export default Square;

(if the random number is 1 , run the function on the parent that add the number to array) And you can see that when i run it the array is not based on the true or false, it is just adding numbers : (supposed to show only the light colors in the array..)

Image of the problem in chrome

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You would create an addNumber method in the parent, and pass it to the child as a prop. User, interacting with the child, calls the addNumber, pushing the new value to the parent.

Function based components are a better way to do all of this, as opposed to the legacy class based components.

about 4 years ago · Juan Pablo Isaza Report

0

You can pass a method from your parent component to the child component as props.

Here simple example:

const { useState, useCallback } = React;
    
    function Child({ onChange }) {
      return <input type="text" onChange={(e) => onChange(e.target.value)} />;
    }
    
    function App() {
      const [name, setName] = React.useState("");
    
      const handleClick = useCallback((e) => {
        setName(e);
      }, []);
    
      return (
        <div>
          <div>{name}</div>
          <Child onChange={handleClick} />
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!