Skip to content

[FR] Provide a onRender prop in ServerSideRender #35294

@pryley

Description

@pryley

What problem does this address?

Sometimes you need to trigger some javascript after a block is rendered with ServerSideRender.

Previously, the solution was to extend the ServerSideRender class. However with WordPress 5.8 this is no longer easily possible due to the changes made to allow Blocks to work outside of the post editor (i.e. sidebars and widgets).

See also:

What is your proposed solution?

My suggestion is to include a onRender prop to ServerSideRender and trigger it with the useEffect hook:

export default function ServerSideRender (props) {
    const {
        attributes,
        block,
        className,
        httpMethod = 'GET',
        onRender, // <- Here is the new "onRender" prop
        urlQueryArgs,
        EmptyResponsePlaceholder = DefaultEmptyResponsePlaceholder,
        ErrorResponsePlaceholder = DefaultErrorResponsePlaceholder,
        LoadingResponsePlaceholder = DefaultLoadingResponsePlaceholder,
    } = props;

    // ... 

    // Here is how the "onRender" prop is used
    useEffect(() => {
        if (onRender) {
            // Here we pass the response, the block, and attributes used for the response
            onRender(response, block, attributes);
        }
    }, [response]);

    // ... 

    return <RawHTML className={ className }>{ response }</RawHTML>;
}

And this is how you would use it in your block:

const onRender = (response, block, attributes) => {
    if (!_.isEmpty(response) && !response.error) {
        console.log('the block has been rendered!');
    }
}

<ServerSideRender block="my/block" attributes={ attributes } onRender={ onRender }></ServerSideRender>

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions