React JSでドロップダウンのonChangeイベントを使いこなして、ユーザーインターフェースをレベルアップ!
React JS でドロップダウンリストの onChange イベントを使用すると、ユーザーがドロップダウンからオプションを選択したときにアクションを実行できます。
この解説で学ぶこと
- ドロップダウンリストと onChange イベントの基本
- React JS で onChange イベントを設定する方法
- onChange イベントで実行できる処理例
必要なもの
- React JS の基本知識
- JavaScript の基本知識
const App = () => {
const [selectedValue, setSelectedValue] = useState('');
const handleChange = (event) => {
setSelectedValue(event.target.value);
};
return (
<div>
<select onChange={handleChange}>
<option value="">選択してください</option>
<option value="1">オプション1</option>
<option value="2">オプション2</option>
<option value="3">オプション3</option>
</select>
<p>選択された値: {selectedValue}</p>
</div>
);
};
コード解説
useState
フックを使って、selectedValue
という状態変数を初期化します。onChange
イベントハンドラー関数を定義します。- イベントハンドラー関数内で、
event.target.value
を使って選択されたオプションの値を取得します。 setSelectedValue
を使って、状態変数を更新します。select
要素にonChange
イベントリスナーを設定し、イベントハンドラー関数を渡します。p
要素を使って、選択された値を表示します。
- 選択された値に基づいて、別のコンポーネントを表示する
- API を呼び出してデータを取得する
- データベースを更新する
- ユーザーにアラートを表示する
- 上記のコードは基本的な例です。必要に応じて、コードをカスタマイズして様々な処理を実行できます。
- onChange イベントだけでなく、他のイベントも同様に使用できます。
補足
useState
フックは、状態変数を管理するための便利なツールです。- イベントハンドラー関数は、イベントが発生したときに呼び出される関数です。
event.target.value
は、イベントが発生した要素の値を取得します。
const App = () => {
const [selectedValue, setSelectedValue] = useState('');
const handleChange = (event) => {
setSelectedValue(event.target.value);
};
return (
<div>
<select onChange={handleChange}>
<option value="">選択してください</option>
<option value="1">オプション1</option>
<option value="2">オプション2</option>
<option value="3">オプション3</option>
</select>
<p>選択された値: {selectedValue}</p>
</div>
);
};
const App = () => {
const [selectedValue, setSelectedValue] = useState('');
const handleChange = (event) => {
setSelectedValue(event.target.value);
};
const renderComponent = () => {
switch (selectedValue) {
case '1':
return <Component1 />;
case '2':
return <Component2 />;
case '3':
return <Component3 />;
default:
return null;
}
};
return (
<div>
<select onChange={handleChange}>
<option value="">選択してください</option>
<option value="1">オプション1</option>
<option value="2">オプション2</option>
<option value="3">オプション3</option>
</select>
{renderComponent()}
</div>
);
};
renderComponent
という関数を定義し、選択された値に基づいて表示するコンポーネントを返します。switch
ステートメントを使って、選択された値に基づいて処理を分岐します。renderComponent
の戻り値をdiv
要素内に表示します。
const App = () => {
const [selectedValue, setSelectedValue] = useState('');
const [data, setData] = useState([]);
const handleChange = (event) => {
setSelectedValue(event.target.value);
fetchData(event.target.value);
};
const fetchData = (value) => {
fetch(`/api/data/${value}`)
.then((response) => response.json())
.then((data) => setData(data));
};
return (
<div>
<select onChange={handleChange}>
<option value="">選択してください</option>
<option value="1">オプション1</option>
<option value="2">オプション2</option>
<option value="3">オプション3</option>
</select>
{data.length > 0 && (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
};
data
という状態変数を定義し、API から取得したデータを格納します。fetchData
関数を定義し、API を呼び出してデータを取得します。onChange
イベントハンドラー関数内で、fetchData
関数を呼び出して選択された値に基づいてデータを取得します。- 取得
ドロップダウンの onChange イベントを使用するその他の方法
イベントオブジェクトのその他のプロパティを使用する
event
オブジェクトには、value
プロパティ以外にも、さまざまなプロパティがあります。 例えば、target
プロパティは、イベントが発生した要素への参照を提供します。
const handleChange = (event) => {
const selectedValue = event.target.value;
const selectedIndex = event.target.selectedIndex;
// ...
};
カスタムイベントを使用する
独自のイベントを作成して、ドロップダウンの onChange イベントに関連するデータを伝達することができます。
const MyComponent = () => {
const [selectedValue, setSelectedValue] = useState('');
const handleChange = (event) => {
const customEvent = new CustomEvent('my-event', {
detail: {
selectedValue: event.target.value,
},
});
window.dispatchEvent(customEvent);
};
return (
<div>
<select onChange={handleChange}>
<option value="">選択してください</option>
<option value="1">オプション1</option>
<option value="2">オプション2</option>
<option value="3">オプション3</option>
</select>
</div>
);
};
const OtherComponent = () => {
useEffect(() => {
window.addEventListener('my-event', (event) => {
const selectedValue = event.detail.selectedValue;
// ...
});
}, []);
return <div>別のコンポーネント</div>;
};
React refsを使用する
ref
を使用して、ドロップダウン要素への直接的な参照を取得することができます。
const App = () => {
const selectRef = useRef();
const handleChange = () => {
const selectedValue = selectRef.current.value;
// ...
};
return (
<div>
<select ref={selectRef} onChange={handleChange}>
<option value="">選択してください</option>
<option value="1">オプション1</option>
<option value="2">オプション2</option>
<option value="3">オプション3</option>
</select>
</div>
);
};
第三者ライブラリを使用する
react-select
などの第三者ライブラリを使用して、ドロップダウンの機能を拡張することができます。
どの方法を使用するかは、要件とプロジェクトのセットアップによって異なります。
ドロップダウンの onChange イベントは、ユーザーがドロップダウンからオプションを選択したときにアクションを実行する便利な方法です。 上記のサンプルコードとその他の方法を参考に、要件に合った方法で onChange イベントを使用してください。
javascript reactjs