reactjsreact-props

Return callback from children of render prop element


Hell. I have some question about render prop pattern.

The component 'ColumnAction' handle table head width adjustment, and reorder of each table head by catching events like mouseDown, and mouseUp. To do so, I passed ref, ref2 as a children.

But, one thing I add more is to catch some action from each child. When each child invoke some events like attribute change, the parent component should catch it, and take another action in main component.

To do so, I tried several changes, and tried to pass props to each child. But all that try are fail. I seems like it is unable to pass prop to render props.

Is there any solution for this? Thanks in advance.

    const TableHead = props.selectedAttributes.map(attribute => {
        
        const attributeDetail = props.attributes.find(attr => attr.attribute === attribute)
        
        return (
            <ColumnAction key={attribute}>
                {
                    ({ ref, ref2 }) => (
                        <th className='UniveralGridTableHead draggable' data-attrb={attribute} data-menu={props.menu} ref={ref2}>
                            {attributeDetail.label}
                            <i
                                className='sortDesc'
                                style={{
                                    display: attributeDetail.sortable ? 'inline-block' : 'none',
                                    borderTop: props.orderBy === attribute && props.orderDirection === 'DESC' ? '5px solid #EEEEEE' : '5px solid #888888'
                                }}
                                onClick={() => props.conditionCallback('sortDesc', attribute)}
                            ></i>
                            <i
                                className='sortAsc'
                                style={{
                                    display: attributeDetail.sortable ? 'inline-block' : 'none',
                                    borderBottom: props.orderBy === attribute && props.orderDirection === 'ASC' ? '5px solid #EEEEEE' : '5px solid #888888'
                                }}
                                onClick={() => props.conditionCallback('sortAsc', attribute)}
                            ></i>
                            <div className='ColumnResizer' ref={ref}></div>
                        </th>
                    )
                }
            </ColumnAction>
        )
    })

Solution

  • Finally, I got a solution, and it was quite simple...

    Parent

    // Pass props to get callback like this
    
    <ColumnAction key={attribute} someCallback={dd => doSomething(dd)}>
    

    Children

    const ColumnAction = props => {
    
        // Declare both chilren and callback props 
        const { children, someCallback } = props
    ...
    
        // Call the callback function when you use
        someCallback('SomeAction')