1

How to use data attributes in React without using quotes (quotes in this case make code less readable)?

const e = React.createElement;

e(
  "span", {
    id: "foo",
    className: "bar",
    "data-tippy-content": "tooltip",
  }, "Foobar"),


... and without using JSX.

2
  • 1
    You can't. Object keys must be either quoted or valid JS identifiers. data-tippy-content is a subtraction, as far as JS is concerned. Commented Jun 16, 2019 at 7:42
  • I was hoping something like dataSet was available. github.com/facebook/react/issues/1259 Commented Jun 16, 2019 at 7:50

1 Answer 1

2

Since you're already not using JSX, you could write a wrapper for React.createElement that transforms dataset: {...} into data- attributes:

const e = (tag, attrs, children) => {
  const { dataset, ...otherAttrs } = attrs;
  if (dataset) {
    for (const key in dataset) {
      otherAttrs[`data-${key}`] = dataset[key];
    }
  }
  return React.createElement(tag, otherAttrs, children);
};

e("h1", {dataset: {"tippy-content": "foo"}}, ...);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.