Home > Net >  How to pass data with Html Attributes after mapped Array without using another React components?
How to pass data with Html Attributes after mapped Array without using another React components?

Time:08-25

I am trying to pass data with HTML attribute without using another component to handleClick but I couldn't handle can anyone help me please

const handleLiClickFirst = (airport) => {
    setFirst(airport.target.innerHTML);
    console.log(airport.target.lat); // I can't read the data here
  };

   <div className="header__first">
        <TextField
          id="outlined-basic"
          label="From"
          variant="outlined"
          value={first}
          onChange={(e) => setFirst(e.target.value.toLocaleLowerCase())}
        />
        <ul>
          {resultFirst.airports?.map((airport, i) => {
            return (
              <li
                key={airport.iata}
                airport={airport}
                onClick={handleLiClickFirst}
                lat={airport.latitude}
                name={airport.name}
                long={airport.longitude}
              >
                {airport.name}  // I can read the data here
              </li>
            );
          })}
        </ul>
      </div>

CodePudding user response:

Random attributes like airport and lat aren't valid to attach to a native HTML element like <li>. However, you should be able to use data attributes instead to store data on an HTML element.

And you will likely need to use data-airport={JSON.stringify(airport)} instead of just passing the JS object. And if you can avoid passing the entire object in, (by saving each of the properties that you need separately, like you are already doing with latitude, for example) that may be best to avoid to prevent creating massive HTML attribute strings.

CodePudding user response:

I solve this problem without attributes and the handleClick Method after I couldn't reach the data. I removed handleClick from onClick and added the code in onClick

        onClick={() => {
              setFirst(airport.name);
              //    setFirstLatlong([airport.latitude,airport.longitude]);
              setFirstLatlong({
                lat: airport.latitude,
                long: airport.longitude,
              });
            }}  

        
                                                                                                                

@Jacob K I will try to use your method on an upcoming project. Thank you

  • Related