Dynamic CSS classes or attributes

If your application uses a dynamic CSS generation or elements have attributes with dynamic values, this article is for you.

You might find this article useful if:

  • your application uses dynamic CSS generation (e.g. Emotion library for React, styles scoping in Angular or others)
  • your application uses dynamic values for different HTML attributes (e.g. data-impl="4547745")

If this is your case, you will end up with non-stable tours and hints. Product Fruits uses CSS selectors to successfully target elements. It is the standard and only way we can target elements in your application. Those selectors use class names or different attribute names/values and if they dynamically change, tours and hints won't work well.

Update your HTML code

We recommend using custom data- attributes. You can add data-component attributes (or similar) to the root elements of your components. This might be helpful not just for Product Fruits, but also for testing frameworks like Cypress or Selenium.

For example, if there is a Save button on your page, with dynamic classes, it might look like this:

<button class="css-4mrg2x7c">Save</button>

You can add the data-component attribute:

<button data-component="MainSaveButton" class="css-4mrg2x7c">Save</button>

For more complex components, it might look like this:

<div data-component="Projects-ListView">
    <h2>My projects</h2>
    <div data-component="Projects-Table">
        <div data-component="Project-Item"></div>
        <div data-component="Project-Item"></div>

React and Babel

If you have a high amount of components, we've seen success with using this Babel plugin. The plugin will generate data- attributes for you automatically.

Tours & hints editor settings

After you have your custom attributes assigned to components, you can set the editor to prefer the data attributes over CSS classes. Without this setting, you would need to adjust the CSS selector manually.

  1. Open the tour or hints editor
  2. Click on the Settings button (the cogwheel icon)
  3. Set the Snap only to elements with these attributes field to the name of your custom attribute, for instance data-component

Now, when you try to target the element, the editor should be trying to find the best CSS selector using your data attribute.