How to add a child element when clicking the cell in Ag-grid?

Viewed 176

I'm trying to add an icon when clicking on the cell. When I click on a cell by using teamFunction in cellRenderer it shows info about the cell. But there is also the method onCellClicked which shows info about the clicked cell too. Both methods are clickable. I need to add an icon when clicking on the cell. I want to return div with icon to the selected cell:

selected cell

In the cell I need to add the child element:

 <div className="checked">
        <FontAwesomeIcon icon={faCheck} color="green"/>
 </div>

In the teams array I have objects with info:

const teams = [
{
  gender: "boys"
  name: "High School Team"
  sport: "Volleyball"
  team_id: "12111"
},
{
  gender: "girls"
  name: "Middle School Team"
  sport: "Baseball"
  team_id: "12222"
},
{
  gender: "boys"
  name: "Students"
  sport: "Bowling"
  team_id: "12333"
},
]

Component:

  const onFirstDataRendered = useCallback(() => {
    ref.current.api.sizeColumnsToFit();
  }, []);

const teamFunction = (params) => {
    return (
      <div className="cell">
        <div>
          <div>{params.data.gender} {params.data.sport}</div>
          <div>{params.data.name}</div>
        </div>
      </div>
    );
  };

  const columnDefs = [
    {
      field: 'team',
      headerName: 'Team',
      cellRenderer: teamFunction,
      resizable: true,
      width: 100,
    },
  ];

  return (
    <AgGridReact
      ref={ref}
      rowData={teams}
      columnDefs={columnDefs}
      defaultColDef={{ resizable: true }}
      rowHeight={60}
      headerHeight={50}
      onFirstDataRendered={onFirstDataRendered}
      onGridSizeChanged={() => onGridSizeChanged(ref)}
    />
1 Answers

I added Hook

const [selectedTeam, setSelectedTeam] = useState(null);

In teamFunction I control selectedTeam:

const teamFunction = (params) => {
   return (
      <div className={styles.cellStyles}>
        <div className={(selectedTeam !== params.data.team_id) ? styles.unSelectedTeam : null}>
          <div className={styles.boldText}>{params.data.gender}{params.data.sport}</div>
          <div>{params.data.name}</div>
        </div>
        {(selectedTeam === params.data.team_id) ? (
          <div className={styles.checked}>
            <FontAwesomeIcon icon={faCheck} color="#22EA72" style={{ fontWeight: 'bold' }} />
          </div>
        ) : null}
      </div>
    );
  };

In columnDefs added onCellClicked:

onCellClicked: cellClicked,

cellClicked function controls the selected team :

const cellClicked = (params) => {
    setSelectedTeam(params.data.team_id);
};
Related