0

I want add a custom attribute (for instance an attribute named "key") in an element using React but I only can add some keywords like "className", "style", etc...

My code right now is like this:

function TodoItem(props){
    return React.createElement("div",{key:props.id,className:"todo-item"},
        React.createElement("input",{type:"checkbox"},null),
        React.createElement("p",null,props.text)
    );
}

I can not add "key:props.id".

My objective would be to create something like this:

<div class="todo-item" key="<int>" data-reactid=".0.0"><input type="checkbox" data-reactid=".0.0.0"><p data-reactid=".0.0.$test">Take out trash</p></div>

Right now I do not know how to put the key="int" part

Lukas
  • 49
  • 2
  • 10
  • [`key` is a reserved prop name.](https://reactjs.org/docs/lists-and-keys.html#keys) – Emile Bergeron Oct 01 '19 at 16:40
  • But how can I add it to the element then? – Lukas Oct 01 '19 at 16:49
  • `key` won't appear as an attribute of the resulting HTML element. If you really want it to appear in the page, you could use `'data-key'` as the prop name. – Emile Bergeron Oct 01 '19 at 17:05
  • Possible duplicate of https://stackoverflow.com/questions/31273093/how-to-add-custom-html-attributes-in-jsx – Asons Oct 01 '19 at 17:05
  • 1
    @EmileBergeron That worked! I could add the "data-key" attribute, however I have a warning that says "Warning: Each child in an array or iterator should have a unique "key" prop", I was trying to add a property called "key" to get rid of that warning.. – Lukas Oct 01 '19 at 17:10
  • Your question is an [XY problem](https://meta.stackexchange.com/q/66377/254800). You're asking about the `key` prop, but really, you want to know how to fix the warning. It's really important that you give the whole context when asking so the answers you receive are on topic and useful to most. – Emile Bergeron Oct 01 '19 at 19:20
  • Possible duplicate of [Getting key prop warning in React, even though key is set](https://stackoverflow.com/questions/32256492/getting-key-prop-warning-in-react-even-though-key-is-set) – Emile Bergeron Oct 01 '19 at 19:21

3 Answers3

3

Just curious, why you dont want to use jsx?

If you want to see the translation you can visit babeljs.io

for example:

function Comp() {
    return <div myprop="prop" />
}

results to:

function Comp() {
 return React.createElement("div", {
    myprop: "prop"
  });
}

And, since i cannot comment yet. key word is reserved as mentioned. So use key so react can render smarter, and some other propname if you want to pass your own stuff.

Edited:

So to have your component as it should be with arrays, do it like so.

function NoJSX(props) {
  return React.createElement(
    "div",
    {
      key: "ishouldbeunique", // a unique value, specially for React
      myKey: "icanbeeverything" // whatever you want
    },
    props.children
  );
}

will result in:

<div myKey="icanbeeverything">test me</div>
Miller
  • 311
  • 1
  • 5
  • For what I know I need to parse the JSX to be converted to js, right now I want to jump that part and just use vanilla javascript while learning React. I will eventually in the future use JSX. – Lukas Oct 01 '19 at 16:47
  • 1
    With create-react-app all that stuff is handled for you. I love JSX, give it a chance is my advice :) Or, if that is a step to far, you can mess around with codesandbox.io. – Miller Oct 01 '19 at 16:51
  • Yeah I know that JSX is one of the best features of react, I was thinking to use that later, but it seems that since I got this problem with vanilla javascript it is a good opportunity to start using JSX and get the problem solved. However it would be nice to have an answer to this question. Thanks for the tips anyway :) – Lukas Oct 01 '19 at 16:59
  • 1
    What do you mean by `I can not add "key:props.id"` for me it works fine, check here: https://codesandbox.io/s/wonderful-river-zr9kb – Miller Oct 01 '19 at 16:59
  • Maybe I did not see right but I do not see the "key" attribute in the created element... – Lukas Oct 01 '19 at 17:05
  • Indeed, because its used internally by react. Try, `customKey:props.id`. – Miller Oct 01 '19 at 17:08
  • Check my last update, there you see NoJSX component and its output. – Miller Oct 01 '19 at 17:12
1

The following example uses the key prop and so, it will not show the warning.

function TodoItem({ arr }) {
  return arr.map(item =>
    React.createElement(
      "div",
      {
        key: item.id, // <--- Put the key prop here.
        className: "todo-item"
      },
      React.createElement("input", { type: "checkbox" }, null),
      React.createElement("p", null, item.text)
    )
  );
}

const data = [
  { id: 1, text: "Box 1" },
  { id: 2, text: "Box 2" }
];

const rootElement = document.getElementById("root");
ReactDOM.render(React.createElement(TodoItem, { arr: data }), rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

key:props.id: I see it still ok with me

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
aldenn
  • 2,060
  • 2
  • 11
  • 30
  • Thanks for the help! That is what I was exactly looking for. Right now I am not in the computer but later I will try to adapt your code to my problem and try to solve it. – Lukas Oct 01 '19 at 17:20
  • 1
    I moved the codesandbox example to a on-site stack snippet since your answer was incomplete without the code itself. I changed it a little to focus on the solution and reduced the noise and duplication around it. Feel free to edit it to your liking. Sorry if it changed too much ;) – Emile Bergeron Oct 01 '19 at 19:17
0

Using data attributes

HTML5 is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes...

According to developer.mozilla.org if you want to specify a custom attribute, use data-[customName] like data-key in your case.

Use this format: 'attribute':'key'

var elm = React.createElement(
    /* element          */ 'h1'
    /* custom attribute */ ,{'data-key': 'todo-item'}
    /* innerHTML        */ ,'Hello'
)

ReactDOM.render(
   elm,
   document.getElementById('root')
)

HTML DOM Result:

<div id="root">
   <h1 data-key="todo-item">Hello</h1>
</div>

If you want to add class attribute use commas {'data-key': 'todo-item', className: 'myClass'}

vincent thorpe
  • 171
  • 1
  • 10