Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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>;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading