Home > Enterprise >  Accessing state or props from functional component
Accessing state or props from functional component

Time:08-28

i'm trying to accessing variable/state in functional component from other component. i found out i can save the in some global state like redux or local storage. but i don't want to use any of them. i also found out about lifting state up but can't understand about it.

below is an example for my case. let's say i want to generate a lucky number from functional component GenerateLuckyNumber. and i call the component from showLuckyNumber. but i need to save all the list of lucky number that have been generated. i create a hook state to store all lucky number. but i dont know how to retrieve them from GenereateLuckyNumber

any idea how to to it?

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { useState, useEffect } from 'react';

export const GenerateLuckyNumber = () => {
  const [luckNo, setluckNo] = useState(1)
  
  const changeCatName = () => {
    setluckNo(Math.floor(Math.random() * 100))
  }
  
  return (
  <>
  <TouchableOpacity onPress={() => changeCatName()}>
    <Text>Hello, Your Lucky Number is {luckNo}!</Text>
  </TouchableOpacity>
  </>
  );
}

const showLuckyNumber = () => {
  const [listLuckyNumber, setlistLuckyNumber] = useState()
  //how to save all generated number from functional component to state in this component
  
  return (
  <>
    <GenerateLuckyNumber/>
    <GenerateLuckyNumber/>
    <GenerateLuckyNumber/>
  </>
  );
}

export default showLuckyNumber;

CodePudding user response:

Your component can provide an optional callback function as a prop, which it would invoke whenever it "generates a lucky number". For example:

export const GenerateLuckyNumber = ({onGenerate}) => {

And within the component:

const changeCatName = () => {
  const luckyNumber = Math.floor(Math.random() * 100);
  setluckNo(luckyNumber);
  onGenerate && onGenerate(luckyNumber); // invoke the callback
}

Then any component which renders a <GenerateLuckyNumber/> can optionally supply it with a callback:

const showLuckyNumber = () => {
  const [listLuckyNumber, setlistLuckyNumber] = useState()
  
  const handleNewLuckyNumber = (num) => {
    // do whatever you like with the newly generated number here
  };
  
  return (
  <>
    <GenerateLuckyNumber onGenerate={handleNewLuckyNumber}/>
    <GenerateLuckyNumber onGenerate={handleNewLuckyNumber}/>
    <GenerateLuckyNumber onGenerate={handleNewLuckyNumber}/>
  </>
  );
}
  • Related