1

I have a array of objects called data in fact it take from API in real code, I can not change its structure. so I want to display data in a table, it has a nested objects called list which contains location and price, I want to display as select option when user change location display own price front of it.

{data.serverTypes.map((Item, Index) => {
return (
  <tr key={Index}>
    <td>{Item.id}</td>
    <td>
      <select onChange={(e) => setPrice(e.target.value)}>
        {Item.list.map((Location, Idx) => {
          return (
            <option value={Location.price}>
              {Location.location}
            </option>
          );
        })}
      </select>
    </td>
    <td>{price}</td>
  </tr>
);
})}

But I can not figure out how can I display each price form each location when I iterate object because I define state outside of loop. for better understanding please see live demo, change select option to see result. already it display price for all, but I want to display each location's price front of it.

Demo

1

1 Answer 1

1

Consider creating a child component for each ServerType to hold its own state.

Also, you are selecting a location, not selecting a price. So price can be derived from selectedLocation.

export default function App() {
  const data = {
    serverTypes: [
      {
        id: 1,
        list: [
          { location: "usa", price: 1000 },
          { location: "germany", price: 2000 }
        ]
      },
      {
        id: 2,
        list: [
          { location: "usa", price: 2500 },
          { location: "germany", price: 3000 }
        ]
      }
    ]
  };

  return (
    <div className="App">
      <table>
        <thead>
          <tr>
            <th>id</th>
            <th>location</th>
            <th>price</th>
          </tr>
        </thead>
        <thead>
          {data.serverTypes.map((serverType, index) => (
            <ServerType key={index} serverType={serverType} />
          ))}
        </thead>
      </table>
    </div>
  );
}

const ServerType = ({ serverType }) => {
  const [selectedLocation, setSelectedLocation] = useState(0);
  const { id, list } = serverType;
  return (
    <tr>
      <td>{id}</td>
      <td>
        <select onChange={({ target }) => setSelectedLocation(target.value)}>
          {list.map(({ location }, index) => {
            return <option value={index}>{location}</option>;
          })}
        </select>
      </td>
      <td>{list[selectedLocation].price}</td>
    </tr>
  );
};

Edit eager-jones-v3kih3

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.