Home > Net >  How can I get the variable from other function to another component on React?
How can I get the variable from other function to another component on React?

Time:08-25

Is that possible to use a variable of different function in another component ? I seperated function part and component part that is like :

design structure

and my function:

export function createCombos(number_of_cells) {
  number_of_cells = parseInt(number_of_cells);
  const real_number = Math.sqrt(number_of_cells);
  const arr = Array(real_number)
    .fill(0)
    .map((x) => Array(real_number).fill(0));
}

I want to use "arr" which I declared in "createCombos" function.

The component that I wanted to use in : Board.js

I want to use like that :

import { createCombos } from "../functions/Combo";
import { useEffect, useState } from "react";
export default function Board() {
  var [arra, setArra] = useState([]);
  useEffect(() => {
    createCombos(prompt("enter a number:"));
     **setArra(createCombos.arr);**
  });
  return <div>
     **arra.map((a)=> { 
        <p> {a} </p> 
         })**
    </div>;
}

How can I do that? Thanks!

CodePudding user response:

in Combo.js, return the array from createCombos function.

export function createCombos(number_of_cells) {
  number_of_cells = parseInt(number_of_cells);
  const real_number = Math.sqrt(number_of_cells);
  const arr = Array(real_number)
    .fill(0)
    .map((x) => Array(real_number).fill(0));
  return arr
}

change the React component to this.

import { createCombos } from "../functions/Combo";
import { useEffect, useState } from "react";
export default function Board() {
  var [arra, setArra] = useState([]);
  useEffect(() => {
   // save returned array to arr variable
    const arr = createCombos(prompt("enter a number:"));
    setArra(arr);
  });
  return <div>
     arra.map((a)=> { 
        <p> {a} </p> 
         })
    </div>;
}
  • Related