Home > Software design >  How can I call the function of a parent component inside of a child component?
How can I call the function of a parent component inside of a child component?

Time:11-16

First off, I'm newer to react so please feel free to critique any sort of architectural problems I have, I feel like there's a better way to write this but I've been struggling for an hour trying to get it to work.

Parent Element (TileGrid):

import React, { Component } from 'react'
import Tile from './Tile.js';

export default class TileGrid extends Component {
    constructor(props) {
        super(props);
    }

    updateTileData(value) {
        {/* Do something with value here */}
    }

    render() {
        this.test()
        return (
            {/* The Tile component is a custom button with some richer features. */}
            <Tile name='Dog' image='dog' /> 
        )
    }
}

Child Element (Tile):

import React from 'react';
import ButtonBase from '@mui/material/ButtonBase';
import './styles/Tile.css';

function Tile(props) {
    return(
        <div className="Tile">
            <ButtonBase onClick={/* This is where the Tile needs to call updateTileData in TileGrid */}>
            Button
            </ButtonBase>
        </div>
    );
}

export default Tile;

So there's a function inside of TileGrid called updateTileData that is going to take some data and use it to update the state of TileGrid. The Tile component exists as a child within the TileGrid component. I've tried all sorts of stuff on here but this seems like a simple task to do, is there a better way to write this functionality? I'm not tied down to anything in the code, please tell me if there's a better way to do this. I'm still learning this framework and this issue has me hung up. Thanks, Archer.

CodePudding user response:

pass the function from parent to child as a prop example :

<Child func={this.functionInParent} />

props.func() //called inside child

CodePudding user response:

you need to pass a prop to child Element and Call it.

  import React, { Component } from 'react'
    import Tile from './Tile.js';
    
    export default class TileGrid extends Component {
      
 
    updateTileData(value) {
        {/* Do something with value here */}
    }

   

    render() {
        this.test()
        return (
            {/* The Tile component is a custom button with some richer features. */}
            <Tile name='Dog' image='dog' setValue={this.updateTileData} /> 
        )
    }
}

child Element :

import React from 'react';
import ButtonBase from '@mui/material/ButtonBase';
import './styles/Tile.css';

function Tile(props) {
    return(
        <div className="Tile">
            <ButtonBase onClick={()=>props.setValue("your value")}>
            Button
            </ButtonBase>
        </div>
    );
}

export default Tile;
  • Related