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

7
  • key is a reserved prop name. Commented Oct 1, 2019 at 16:40
  • But how can I add it to the element then? Commented Oct 1, 2019 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. Commented Oct 1, 2019 at 17:05
  • Possible duplicate of stackoverflow.com/questions/31273093/… Commented Oct 1, 2019 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.. Commented Oct 1, 2019 at 17:10

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

7 Comments

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.
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.
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 :)
What do you mean by I can not add "key:props.id" for me it works fine, check here: codesandbox.io/s/wonderful-river-zr9kb
Maybe I did not see right but I do not see the "key" attribute in the created element...
|
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

2 Comments

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.
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 ;)
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'}

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.