Create unique class names for Gutenberg Blocks (admin)

I was working on a Gutenberg block recently, and I needed to be able to show a unique preview for each block when they clicked a “Preview” button. So I needed a better way to select the class names with my JavaScript, and thus had to find a way to make each class name unique. This is particularly helpful if you are using <ServerSideRender> to output.

In order to add a unique ID to your element, you can use the props value for clientId like this: props.clientId

So for example in your JSX it could look a bit like this:

ssr = <div class={'my-unique-class-' + props.clientId}>
                    <ServerSideRender
                        block="custom/block"
                        attributes={{
                            username: attributes.username,
                        }}></ServerSideRender>
                </div>

Then when you want to access this particular element it could look something like

function handleSomeAction() {
    const elem = document.querySelector('.my-unique-class-' + props.clientId);
}

I was able to find this out on my own by just doing a console.log( props ) to see which variables were available to me. But there is also a Stack Overflow thread about it I came across later as well. See resources.