skip to Main Content

I have a functional component:

function Tile(props: any) {

  const selectTile = (() => {
    ...
  })

  return (
    <div>
      ...
    </div>
  )
}

I then create another functional component which will hold many tiles.

function Grid(props: any) {

  const selectAllTiles = (() => {
    
  })

  return (
    <div>
      <Tile></Tile>
      <Tile></Tile>
      <Tile></Tile>
    </div>
  )
}

My question is, how can I call the selectTile() function for each Tile within the selectAllTiles() function? What approaches are there?

2

Answers


  1. why don’t use like this:

        function Tile(props: any) {
        
          return (
            <div>
              ...
            </div>
          )
        }
        
       const selectTile = (() => {
            ...
         })
    
    Login or Signup to reply.
  2. I would make the parent component keep track of selected tiles, and it will then inform each Tile (through props) if it is selected or not.

    If a Tile should be able to "make itself selected", then a function can be passed from the parent into each Tile (also through props) that the Tile can call and which will update the selected tiles collection in the parent.

    Updated code:

    function Tile(props: any) {
      const { isSelected, makeSelected } = props;
    
      return (
        <div style={{ ... something based on isSelected ... }}>
          <button type="button" onClick={makeSelected}>Select me</button>
        </div>
      )
    }
    
    function Grid(props: any) {
    
      const [isSelected, setIsSelected] = useState<bool[]>([false, false, false]);
    
      const makeSelected = (index: int) => {
        // ...
        setIsSelected(...);
      }
    
      return (
        <div>
          <Tile isSelected={isSelected[0]} makeSelected={() => makeSelected(0)}></Tile>
          <Tile isSelected={isSelected[1]} makeSelected={() => makeSelected(1)}></Tile>
          <Tile isSelected={isSelected[2]} makeSelected={() => makeSelected(2)}></Tile>
        </div>
      )
    }
    

    This is just an (untested) example, many approaches are possible.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search