Novato para reaccionar aquí.
TLDR: tengo una función auxiliar llamada createNotification que, cuando se llama, inserta un <ToastNotification /> en un elemento container usando render(). Si uso createPortal() no se agrega nada. Si uso render, el componente solo se agrega una vez a pesar de múltiples activadores.
¿Alguien puede ayudarme a averiguar qué está pasando, por favor?
Gracias
ayudantes.js
import { ToastNotification } from "carbon-components-react"; import { render, createPortal } from "react-dom"; export const createNotification = () => { const container = document.getElementById("notificationContainer"); console.log(container); //just to check function is running and has found container return render(<ToastNotification />, container); //works but only once, not on multiple triggers return createPortal(<ToastNotification />, container); //doesn't render anything in container };la función anterior se llama desde otros componentes según sea necesario:
iniciar sesión.js
import { createNotification } from "../../helpers"; const Login = () => { const validateLogin = async (event) => { createNotification(); // validation logic performLogin(); }; const performLogin = async () => { //axios call here }; // main component content return ( <> <!-- validateLogin() called on form submit --> </> ); }; export default Login;aplicación.js
//imports function App() { return ( <div> <div className="App"></div> </div> ); } export default App;Gracias
Resolví esto yo mismo agregando createPortal() dentro de render() .
Si alguien puede dar una explicación, sería muy apreciada.
export const createNotification = () => { const container = document.getElementById("notificationContainer"); console.log(container); return render(createPortal(<ToastNotification />, container), document.createElement("div")); };createNotification no está montado en el componente de la aplicación Virtual Dom ... cuando usa render (createPortal), simplemente crea una aplicación lanzada.
import { createNotification } from "../../helpers"; export const createNotification = () => { const container = document.getElementById("notificationContainer"); console.log(container); //just to check function is running and has found container return createPortal(<ToastNotification />, container); //doesn't render anything in container }; const Login = () => { const [validate, setValidate] = useState(false); const validateLogin = async (event) => { if('some logic') return setValidte(true) setVAlidte(false) }; useEffect(() => { if(!valite) return; //axios heare }, [validate]) // main component content return ( <> {!validate && <CreateNotfication/>} <!-- validateLogin() called on form submit --> </> ); };