Last active
November 10, 2024 19:22
-
-
Save yukikim/1e41909902bdcec96336b880f7b4329b to your computer and use it in GitHub Desktop.
[tsx]useState を使った簡単な条件分岐
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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