日本語

“React: Show a Text Input Only When ‘Other’ Is Selected”

​​React​Forms,Playwright,TypeScript,useState

To show a free-text input only when "Other" is selected in a survey or contact form, keep the selected value in state and render the input with && only when that value is 'other'. Even if the input has required, it isn't rendered while it's hidden, so people who chose another option can still submit. When sending, check whether the selected option is "Other" before using the input's value.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, React 19.3.1, TypeScript 7.0.2, Playwright 1.63.0, and Chromium 153. I bundled the code with esbuild, loaded it into Chromium with Playwright, operated the radio buttons and dropdowns, and checked whether the input was present, its value, its focus, and the content that was submitted. I did not test Firefox, Safari, or smartphones.

Screen showing the question 'How did you hear about this site?' with four radio buttons: Search, SNS, From an acquaintance, and Other. (The labels in the image are in Japanese.) First, pressing SNS does not show the input. Second, pressing Other shows an input below it with focus, and 'podcast' is typed in. Third, pressing Search hides the input. Fourth, pressing Other shows the input again with 'podcast' still in it. Only at the moment of each press, the result display below and the input border turn pink.
The text input appears only when 'Other’ is selected. Text typed in it stays there even after selecting another option and coming back. The cursor, the circle at the press position, the result display below, and the faint placeholder text meaning 'specifically’ in the input were added for the recording. (The labels in the image are in Japanese.)

Render the Input with && Only When "Other" Is Selected

Keep the value selected with the radio buttons in a state called source, and the free-text value in a state called otherText. Writing source === 'other' && (...) renders the input only when the condition is true, and nothing otherwise. This is the logical AND usage from React's official guide on conditional rendering.

tsx
import { useState, type FormEvent } from 'react';

const options = [
  { value: 'search', label: '検索' },
  { value: 'sns', label: 'SNS' },
  { value: 'friend', label: '知人から' },
  { value: 'other', label: 'その他' },
];

export function RadioWithOther() {
  const [source, setSource] = useState('');
  const [otherText, setOtherText] = useState('');

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const answer = source === 'other' ? otherText.trim() : source;
    showResult({ answer, formData: Object.fromEntries(new FormData(e.currentTarget)) });
  }

  return (
    <form onSubmit={handleSubmit}>
      <fieldset>
        <legend>このサイトを何で知りましたか</legend>
        {options.map((o) => (
          <label key={o.value}>
            <input
              type="radio"
              name="source"
              value={o.value}
              checked={source === o.value}
              onChange={(e) => setSource(e.target.value)}
              required
            />
            {o.label}
          </label>
        ))}
        {source === 'other' && (
          <input
            type="text"
            name="sourceOther"
            aria-label="その他の内容"
            value={otherText}
            onChange={(e) => setOtherText(e.target.value)}
            autoFocus
            required
          />
        )}
      </fieldset>
      <button type="submit">送信</button>
    </form>
  );
}

showResult is a function that writes the submitted content to the screen for testing. In a real form, you would call the code that sends the data to the server here.

In the test environment, the input was absent at first. Right after choosing "Other," the input appeared and received focus. autoFocus is a prop that, according to React's input reference, makes React focus the element when it mounts if the value is true.

When I chose "Other," left the input empty, and submitted the form, the browser's validation stopped the submission and nothing was sent. On the other hand, when I chose "Search" and submitted, the submission went through. The input isn't rendered in that case, so required doesn't apply.

When Sending, Check the Selected Option Before Using the Input's Value

Even if you type text under "Other" and then switch to "Search," the otherText state still holds the typed text. So the value to send is decided by whether source is 'other', not by whether otherText has a value. The answer line in the code above does this.

The submission results in the test environment were as follows:

Action answer Contents of FormData
Under "Other," type ポッドキャスト (with a trailing space) and submit "ポッドキャスト" source: "other", sourceOther: "ポッドキャスト "
Then switch to "Search" and submit "search" Only source: "search"

When collecting values with FormData, the values of inputs that aren't rendered are not included. The free-text value is used after trim() removes the leading and trailing whitespace.

Keeping the Input's Value in State Preserves the Text When the Option Is Changed

Removing an element with && takes it off the screen. As React's official guide on preserving and resetting state explains, when React removes a part that is no longer rendered, it also discards the state inside that part. So where you keep the typed text determines what happens when the user changes options.

With the code above, the text is kept in the parent's otherText and passed in through value. Switching "Other" → "Search" → "Other" restored the typed text in the input, including trailing spaces. The GIF at the top shows this behavior.

If you don't pass value and don't keep the text in state, the same operations left the input empty. The typed text was lost along with the removed input element.

tsx
{source === 'other' && <input type="text" name="sourceOther" aria-label="その他の内容" />}

Choose between these based on whether you want the input to reset when the option changes or keep the typed text.

With hidden Alone, the Form Can't Be Submitted Even When Another Option Is Chosen

You can also keep the input rendered and hide it with the hidden attribute, as explained in MDN's hidden attribute reference. However, if you keep required on a hidden input, the form can't be submitted even when another option is chosen.

tsx
<input type="text" name="sourceOther" aria-label="その他の内容"
  hidden={source !== 'other'} required />

In the test environment, choosing "Search" and pressing the submit button did not submit the form. The hidden input was empty, so validity.valueMissing was true, and the Chromium console showed this error:

text
An invalid form control with name='sourceOther' is not focusable.

Also, after typing ポッドキャスト under "Other," switching to "Search," and submitting, FormData still contained sourceOther: "ポッドキャスト". Hidden fields are still sent as part of the form.

If you want to keep the element but hide it, also add disabled while it's hidden:

tsx
const isOther = source === 'other';

<input type="text" name="sourceOther" aria-label="その他の内容"
  hidden={!isOther} disabled={!isOther} required />

MDN's disabled attribute reference says that disabled controls are not subject to constraint validation and are not sent with the form. In the test environment, choosing "Search" submitted without any problem, and FormData contained only source: "search". Choosing "Other" and submitting with the input empty was stopped, and the typed text remained after switching options.

The Same Approach Works with a Dropdown

When "Other" is one of the <select> options, keep the selected value in state and render the input with the same condition.

tsx
export function SelectWithOther() {
  const [source, setSource] = useState('');
  const [otherText, setOtherText] = useState('');
  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      showResult({ answer: source === 'other' ? otherText.trim() : source });
    }}>
      <label>
        このサイトを何で知りましたか
        <select value={source} onChange={(e) => setSource(e.target.value)} required>
          <option value="">選んでください</option>
          {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </label>
      {source === 'other' && (
        <input type="text" aria-label="その他の内容" value={otherText}
          onChange={(e) => setOtherText(e.target.value)} autoFocus required />
      )}
      <button type="submit">送信</button>
    </form>
  );
}

In the test environment, choosing "Other" showed the input and gave it focus. After typing 雑誌 (magazine) and submitting, answer was "雑誌". Switching to "SNS" hid the input, and the submitted answer was "sns".

​Posted by 86