Search code examples
javascriptreactjsreact-hooksreact-redux

how to show textfield or 2 different component in react js?


I have two components in my demo application (Autocomplete and Text Field). I want to show only one component at any given time. The condition is that when the user uses SLASH (/), it will show the Text Field component; otherwise, it will show Autocomplete.

I tried like this

 export default function ComboBox() {
  const [show, setShow] = React.useState(false);
  const [value, setvalue] = React.useState('');
  const onchange = (e) => {
    const inputValue = event?.target?.value || newValue || '';

    setvalue(inputValue);
    setShow((prevState) => {
      const newState = inputValue?.includes('/');
      if (prevState !== newState) {
        if (newState) {
          setTimeout(() => {
            document.getElementById('outlined-basic')?.focus();
          }, 10);
        } else {
          setTimeout(() => {
            document.getElementById('combo-box-demo')?.focus();
          }, 10);
        }
      }
      return newState;
    });
  };

  return (
    <div>
      {show ? (
        <TextField
          id="outlined-basic"
          label="Outlined"
          variant="outlined"
          value={value}
          onChange={onchange}
        />
      ) : (
        <Autocomplete
          disablePortal
          id="combo-box-demo"
          options={top100Films}
          inputValue={value}
          // defaultValue={'abc'}
          onInputChange={onchange}
          sx={{ width: 300 }}
          renderInput={(params) => <TextField {...params} label="Movie" />}
        />
      )}
    </div>
  );
}

here is my code https://stackblitz.com/edit/react-pjhf7s?file=Demo.tsx

My initial rendering is correct; the Autocomplete component is visible. When the user enters the text 'the/', it correctly shows the Text Field component. However, when I remove the '/', it shows the Autocomplete component, but without the text automatically populating in the Autocomplete component. steps to reproduce

  1. Run application
  2. Enter "the" in autocomplete it will show filter list
  3. Enter "/" .. it will show text field with text "the/" . which correct.
  4. Remove "/"
  5. Autocomplete field is blank .. This is the issue

Expected output : after remove "/" it will show same behavior as point 2


Solution

  • Instead of trying to conditionally render one input or the other, and manage the tangled mess of input value and focused state between the two, I suggest you may be interested in using the freeSolo prop value on the AutoComplete component to allow users to enter any text they please. You can conditionally apply this prop based on the current input value.

    Example:

    export default function ComboBox() {
      const [value, setValue] = React.useState('');
    
      const handleInputChange = (event: React.SyntheticEvent, value: string) => {
        setValue(value);
      };
    
      return (
        <div>
          <Autocomplete
            disablePortal
            freeSolo={value.includes('/')} // <-- ***
            id="combo-box-demo"
            inputValue={value}
            onInputChange={handleInputChange}
            options={top100Films}
            renderInput={(params) => <TextField {...params} label="Movie" />}
            sx={{ width: 300 }}
          />
        </div>
      );
    }