The Dropdown does not render when I click the button. I followed an example, but apparently missing something. Knowing the "why" is most important. Also I’d like to make the ToggleVisibility able to handle any component.
function App() {
return (
<div className="container">
<Header />
<ToggleVisibility Basicexample={MyDropdown} />
<Footer />
</div>
);
}
function Header() {
// const style = { color: "red", fontSize: "48px", textTransform: "uppercase" };
const style = {};
return (
<header className="header">
<h1 style={style}>Goals</h1>
</header>
);
}
function Footer() {
return (
<footer className="footer">
</footer>
);
}
function ToggleVisibility ({basicexample:MyDropdown }) {
// React state to manage visibility
const [show, setShow] = useState();
// function to toggle the boolean value
function toggleShow() {
setShow(!show);
}
var buttonText = show ? "Hide Component" : "Show Component";
return (
<div className="component-container">
<button onClick={toggleShow}>{buttonText}</button>
{show && MyDropdown}
</div>
);
}
function MyDropdown() {
return (
<Dropdown>
<Dropdown.Toggle variant="success" id="dropdown-basic">
Dropdown Button
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1">Action</Dropdown.Item>
<Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
<Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
);
}
>Solution :
You confused the props name and the component name in the ToggleVisibility method. I would reccomend to check how we pass components as props here.
For this situation, the working code:
import React, {useState} from 'react';
export function App() {
return (
<div className="container">
<ToggleVisibility basicexample={<MyDropdown/>} />
</div>
);
}
function ToggleVisibility ({ basicexample }) {
// React state to manage visibility
const [show, setShow] = useState(false);
// function to toggle the boolean value
function toggleShow() {
setShow(show=>!show);
}
var buttonText = show ? "Hide Component" : "Show Component";
return (
<div className="component-container">
<button onClick={toggleShow}>{buttonText}</button>
{show && basicexample}
</div>
);
}
function MyDropdown() {
return (
<div>"here is a dropdown"</div>
);
}
You can play with the code here.