S
S
Sergey2021-03-14 12:25:36
React
Sergey, 2021-03-14 12:25:36

How to display the desired position depending on the choice of the select option?

Hello!

Help solve the problem.
It is necessary to display the desired price when choosing an option in the select. Price and period are in the same object.

Here is the code:

function App() {
  const [state, setState] = useState([]);
  return (
    <>
      {data.map(({ name, variants, id, code }) => {
        return (
          <div key={code + id} className="d-flex">
            <div>{name}</div>
            <select
              onChange={(e) => {
                setState((prev) => {
                  return [...prev, { id: e.target.value }];
                });
              }}
            >
              {variants.map(({ id, data }) => (
                <option key={id} value={id}>
                  {data.period}
                </option>
              ))}
            </select>
            {variants.map(({ price, id }) => (
              <div
                key={id}
                style={{ color: state.id === id ? "yellow" : "red" }}
              >
                {price}
              </div>
            ))}
          </div>
        );
      })}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-03-14
@justedoit

const [ selected, setSelected ] = useState({});

const onChange = ({ target: { value, dataset: { id } } }) => {
  setSelected({ ...selected, [id]: value });
};

return (
  <div>
    {data.map(({ id, name, variants }) => (
      <div>
        <div>{name}</div>
        <select
          value={selected[id]}
          data-id={id}
          onChange={onChange}
        >
          <option>ну давай, выбери что-нибудь</option>
          {variants.map(n => <option value={n.price}>{n.data.period}</option>)}
        </select>
        <div>{selected[id] || 'НИЧЕГО НЕ ВЫБРАНО'}</div>
      </div>
    ))}
  </div>
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question