Search code examples
reactjscomponentsparent-childreact-props

React pass params to the node elements from child component


I need to pass params from child component to the node elements from parent props.

Page component

export default function Categories() {   const dispatch = useDispatch();

  useEffect(() => {
    dispatch(loaderAction(false));

    return () => dispatch(loaderAction(true));   }, [dispatch]);

  function handleClick(params) {
    alert();   }

  function handleEditClick(params) {
    alert();   }

  return (
    <div className="categories-body">
      <div className="categories-header">
        <div className="left">
          <h2>{t('[categories]')}</h2>
        </div>
        <div className="right">
          <button className="button orange">{t('[addNewCategory]')}</button>
          <LanguageSettings name="categoriesLanguageSetting" />
        </div>
      </div>

      // Table component imported
      <Table
        action={
          <>
            //node elements
            <button onClick={handleClick}>save</button>
            <button onClick={handleEditClick}>edit</button>
          </>
        }
      />
    </div>   );  }

TableComponent

export default function Table({action}) {
  return (
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>date</th>
          <th>key</th>
          <th>category</th>
          <th>actions</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
          <td>{action}</td> //pass parameter to node props 
        </tr>
      </tbody>
    </table>
  );
}

I have pass two buttons to the Table component and need to pass for example row id to button onClick


Solution

  • Just pass the function... not the component

    const handleClick = id => alert();
    
    <Table  action={handleClick} />
    
    function Table({action}) {
      return (
        <table>
          ...
          <td><button onClick={() => action(`someId`)}>action</button></td>
        </table>
      );
    }
    

    Or if you insist, pass a function component not an element:

    actions={({id}) =>  <button onClick={() => handleClick(id)}>save</button>}
    
    // Usage
    function Table({action}) {
      const Action = props.action;
      return (
        <table>
          ...
          <td><Action id="Some id"/></td>
        </table>
      );
    }