Set many attributes to object

Hello

I’ve created script which use function adding atributes to one object and I have problem cause I can’t get attributes from array of objects
and set this elements to one object. I’ve tryed by mapping and forEach loop

CODE:

import React from "react";
import ReactDOM from 'react-dom/client';
import { useState } from 'react';

function AttributeFromList(){
    
    
    const listOfAttributes = [

    {nameOfAttribute: "class_of_car", valueOfAttribute: "economy_car"},
    {nameOfAttribute: "color_of_car", valueOfAttribute: "red"},
    {nameOfAttribute: "year_of_production", valueOfAttribute: 2010},
        
]

const executeEvent = (elem, attr) => {

    listOfAttributes.keys(attr).forEach( ev => {
        elem.target.setAttribute(ev, listOfAttributes[ev]);
        
    });
  }
 return(
        <div>
            <button onClick={executeEvent}>Run</button>
        </div>
    )
    
}

const execute = ReactDOM.createRoot(document.getElementById(('root')));
execute.render(<AttributeFromList />)

Without too much detail, attr. are for Html, you have a property name and a value, are you sure the terminology is correct here? The other question might be is this JSX?

Why do you need to set attributes on click?


  • If you want custom HTML attributes, use data attributes.

  • A handler is passed the event object (Synthetic Event in React).

  • .keys() is not needed to loop the array. The first parameter of the forEach callback is passed each of the elements.

  • It might be easier to just have nested arrays of ["attributeName", "attributeValue"]

  • If you don’t actually need the click target, use a ref instead. Avoid direct DOM manipulation in React.


Example
function App() {
  const listOfAttributes = [
    ['date-car-class', 'economy_car'],
    ['date-car-color', 'red'],
    ['date-car-production-year', "2010"],
  ];

  function handleClick({ target }) {
    listOfAttributes.forEach((att) => target.setAttribute(att[0], att[1]));
  }

  return (
    <div>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}

export default App;