React - Select component conditions

0 votes
54 views
added Jan 3 in React by lcjr First Warrant Officer (11,850 points)

Case 

There'll be 2 select components, A & B. 

Select A have 2 options; 1 & 2. If option 1 selected, enable the Select B, else disable it. 

import React, { useState } from 'react';
import Select from 'react-select';

const PocSelect = () => {
  // State to manage the selected options
  const [selectedOptionA, setSelectedOptionA] = useState(null);
  const [selectedOptionB, setSelectedOptionB] = useState(null);

  // Options for the select dropdowns
  const options = [
    { value: 'A', label: 'Option A' },
    { value: 'B', label: 'Option B' },
  ];

  // Handle change when an option is selected for Select A
  const handleChangeA = (selected) => {
    setSelectedOptionA(selected);

    // Clear the selection for Select B when A changes
    setSelectedOptionB(null);
  };

  // Handle change when an option is selected for Select B
  const handleChangeB = (selected) => {
    setSelectedOptionB(selected);
  };

  return (
    <div>
      <h3>Select Component A</h3>
      <Select
        value={selectedOptionA}
        onChange={handleChangeA}
        options={options}
        placeholder="Select an option for A"
      />
      {selectedOptionA && (
        <p>You selected for A: {selectedOptionA.label}</p>
      )}

      <h3>Select Component B</h3>
      <Select
        value={selectedOptionB}
        onChange={handleChangeB}
        options={options}
        placeholder="Select an option for B"
        isDisabled={!selectedOptionA || selectedOptionA.value !== 'B'}
      />
      {selectedOptionB && (
        <p>You selected for B: {selectedOptionB.label}</p>
      )}
    </div>
  );
};

export default PocSelect;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...