Skip to content

Instantly share code, notes, and snippets.

@yukikim
Last active November 10, 2024 19:22
Show Gist options
  • Save yukikim/1e41909902bdcec96336b880f7b4329b to your computer and use it in GitHub Desktop.
Save yukikim/1e41909902bdcec96336b880f7b4329b to your computer and use it in GitHub Desktop.
[tsx]useState を使った簡単な条件分岐
import React, { useState } from 'react';
// それぞれのコンポーネント
const ComponentA: React.FC = () => <div>Component A</div>;
const ComponentB: React.FC = () => <div>Component B</div>;
const ComponentC: React.FC = () => <div>Component C</div>;
const MyComponent: React.FC = () => {
// ステートを定義
const [currentComponent, setCurrentComponent] = useState<string>('A');
// ステートに応じたコンポーネントを切り替え
let renderedComponent;
switch (currentComponent) {
case 'A':
renderedComponent = <ComponentA />;
break;
case 'B':
renderedComponent = <ComponentB />;
break;
case 'C':
renderedComponent = <ComponentC />;
break;
default:
renderedComponent = <div>Invalid Component</div>;
break;
}
return (
<div>
<div>
<button onClick={() => setCurrentComponent('A')}>Show A</button>
<button onClick={() => setCurrentComponent('B')}>Show B</button>
<button onClick={() => setCurrentComponent('C')}>Show C</button>
</div>
{renderedComponent}
</div>
);
};
export default MyComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment