Am trying to render a new ponent onclick a button in react js. Am using functional ponents and I can't handle it. Eg: am in the UserManagement ponent and on a button click I need to render another ponent named employee management.
Am trying to render a new ponent onclick a button in react js. Am using functional ponents and I can't handle it. Eg: am in the UserManagement ponent and on a button click I need to render another ponent named employee management.
Share Improve this question asked Oct 7, 2021 at 6:44 Bismi DavidBismi David 311 silver badge6 bronze badges 1- can you share code ? I think conditional rendering is solution for your problem. – Dostonbek Oripjonov Commented Oct 7, 2021 at 7:04
3 Answers
Reset to default 2You can conditionally
render your ponent.
Example :
EmployeeManagement.js
const EmployeeManagement = () => {
....
return (
<div>
EmployeeManagement
</div>
);
}
UserManagement.js
const UserManagement = () => {
const [hasRender, setRender] = useState(false);
const onShow = React.useCallback(() => setRender(true), []);
return (
<>
<button onClick={onShow}>Show Employee Management</button>
{hasRender && <EmployeeManagement />}
</>
)
}
One way to do this would be to add a local state in UserManagement
,
that holds a boolean
value indication whether the ponent should be hidden or shown.
Then you will have something like:
function UserManagement() {
const [pIsShown, setCompIsShown] = useState(false);
return (
// Whatever else you're rendering.
<button onClick={() => setCompIsShown(true)}>...</button>
{pIsShown && <OtherComp />}
)
}
What will happen is that pIsShown
will initialize as false,
so this condition pIsShown && <OtherComp />
will prevent it from rendering.
Then, when you click the button, the state will set, causing a re-render, except now the condition will be true, so <OtherComp>
will be rendered.
There are other ways to go about this.
Depends mostly on the use-case.
use a visible state & toggle it in onClick:
const [visible, setVisible] = useState(false)
onClick = () => {setVisible(true)}
then render it like this:
{visible && <EmployeeManagement onClick={onClick} />}