I have the following code just to simulate my problem. I would like to conditionally render a component on button click. Here is the code that I have, how do I render the component conditionally using a function and a switch case. Remember I am using only functional components and not class components.
import React from "react";
import ReactDOM from "react-dom";
import One from "./One";
import Two from "./Two";
import Three from "./Three";
import None from "./None";
import "./styles.css";
const handleRender = (e, props) => {
let exp = Math.floor(Math.random() * props);
console.log(exp);
return exp;
};
function Test(exp) {
switch (exp) {
case 1:
return <One />;
case 2:
return <Two />;
case 3:
return <Three />;
default:
return <None />;
}
}
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={(e, p) => handleRender("a", "5")}>
Render One Two or Three
</button>
<Test />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);