Home > Blockchain >  Passing properties from a dynamic Child component to a Parent functional component through a functio
Passing properties from a dynamic Child component to a Parent functional component through a functio

Time:03-29

Parent Body: what I'm trying to do is to pass a function from the child containing a parameter from the dynamic Childs properties so I can access its array indexed state.

export default function MMGrid(props){
    const [tiles, setTiles] = useState(tileSetSetter);//Generate Tiles Array.
    const [test, setTest] = useState();
    
    function resetTiles(){setTiles(tileSetSetter())};
    function clickTile(e) {
        let id = e.target.id;<<<<<<<<========
        
        setTest(id)
        // produces undefined
    }
    
    return(
        <View style={styles.body}>
            <Text>{JSON.stringify(test "Aa")}</Text>
            <MMTile clickTile={resetTiles}  />
            {tiles.map((tile,index) => {
               return (
               <MMTile
                key = {index}
                id = {tile.id} <<<<<<<<==========
                tileColor = {tile.color}
                match= {tile.match}
                isOpen={tile.isOpen}
                clickTile={(e)=>clickTile(e)}
               />)
            })
            }
        </View>
    )

};

Child: is just a shell for the mapping of array in the parent.

export default function MMTile(props) {
    const {color, match, id, isOpen, clickTile} = props;

    function openCheck(){
        if (props.isOpen) {
            return props.tileColor
        } else {return null}
    }


    return (
        <TouchableOpacity style={styles.tile} onPress={clickTile}>
           <View style={[styles.tilecenter, openCheck()]} >
               <Text style={{fontSize : 8}}>{JSON.stringify(props)}</Text>
           </View>
        </TouchableOpacity>
    )
}

CodePudding user response:

You can try the following below code,

  • File Parent.js

import React ,{useState} from 'react'
import Item from './Item'

export default function PassParentChild() {
  const [title,setTitle] = useState("Hello You")
  const ChangeTitle = (value)=>{
      setTitle(value);
  }
  return (
    <div>
        <h1>Parent:{title}</h1>
        <Item title={title} changeTitle = {ChangeTitle} />
    </div>
  )
}

  • Child.js file

import React from 'react'

export default function Item(props) {
  return (
    <div>
        <span>Child :{props.title}</span>
        <button onClick = {()=>props.changeTitle("Hello you you you")}>Change Title</button>
    </div>
  )
}

The Article : PASS DATA BETWEEN REACT COMPONENTS

CodePudding user response:

Here is how I did it

I added the props I needed as a parameter to the onPress() in Childs function so its like this.

 onPress={()=>props.clickTile(props.id)}

an then passed it as it is in the Parent method

    function clickTile(id) {
    setTest(id)
}
  • Related