Quiero renderizar dinámicamente un componente basado en lo que el usuario ha hecho clic. Intenté algo como esto:
function ComponentTest() { const [component, setComponent] = useState<ReactNode | null>(null); return <button onClick={() => setComponent(SomeFunctionalComponent)}>Crash</button> }En este ejemplo, obviamente no estoy haciendo nada con el estado, pero hacer clic en este botón hace que la aplicación se bloquee con los siguientes mensajes de error:
Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks Warning: React has detected a change in the order of Hooks called by EinstellungenTest. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks Uncaught Error: Rendered more hooks than during the previous render. The above error occurred in the <ComponentTest> component:Ahora, podría simplemente escribir
return <button onClick={() => setComponent(<SomeFunctionalComponent/>)}>Crash</button>en cambio, pero creo que eso crea el componente demasiado pronto. Quiero crear el componente durante el renderizado, así:
function ComponentTest() { const [component, setComponent] = useState<ReactNode | null>(null); return <component/> }Espero que alguien pueda ayudarme con esto.
Puede mantener el valor del componente que desea usar en el estado y luego usar la representación condicional para representar el que desea.
Algo como esto
function ComponentTest() { const [componentId, setComponentId] = useState<string | null>(null); return <button onClick={() => setComponent("myId")}> {componentId === "myId" && < SomeFunctionalComponent /> }</button> }