简体   繁体   中英

React Toastr on react application

Hi there I am trying to work on React Toastr and I want to show the toastr notification whenever the success value is active.

Here's what I did so far, first I imported toastr:

import { ToastContainer } from "react-toastr";

Then inside my return statement I've added the div for toatstr:

return ( 
        <>
        <div className="container">
            <ToastContainer ref={ref => container = ref} className="toast" />
        </div>

Next, on my useEffect, I checked if success is true then I can show the toastr:

 useEffect(() => {
         if(userInfo){
             history.push(redirect)
         }
         if(success){
            container.success(`User successfully logged in!`, {
                closeButton: true,
              })
         }
     }, [history, userInfo, redirect, success])

    const submitHandler = (data, e) => {
        e.preventDefault()
        const { email, password } = data
        dispatch(login(email, password))
    }

Here's a complete code for this:

const LoginScreen = ({ location, history }) => {

    const { register, errors, handleSubmit } = useForm()

    const dispatch = useDispatch()
    const userLogin = useSelector(state => state.userLogin)
    const { loading, error, userInfo, success } = userLogin 

    const redirect = location.search ? location.search.split('=')[1] : '/'

     useEffect(() => {
         if(userInfo){
             history.push(redirect)
         }
         if(success){
            container.success(`User successfully logged in!`, {
                closeButton: true,
              })
         }
     }, [history, userInfo, redirect, success])

    const submitHandler = (data, e) => {
        e.preventDefault()
        const { email, password } = data
        dispatch(login(email, password))
    }

    return ( 
        <>
        <div className="container">
            <ToastContainer ref={ref => container = ref} className="toast" />
        </div>
            <h1>Sign In</h1>
           { error && <Message variant='danger'>{error} </Message>}
           { loading && <Loader /> }

         <form onSubmit={handleSubmit(submitHandler)}> 
            <div className="form-group"> 
                <label for="email">Email address</label>
                <input 
                  type="email" 
                  name="email" 
                  className={`form-control ${errors.email ? 'is-invalid' : ''}`}
                  id="email" 
                  placeholder="Enter email" 
                  ref={register({ required: true, minLength: 8, maxLength: 30, pattern: /^\S+@\S+\.\S+$/ })}
                />
                { errors.email && errors.email.type ==='required' && <p className="text-danger">Email is required.</p> }
                { errors.email && errors.email.type ==='minLength' && <p className="text-danger">Email length is too small.</p> }
                { errors.email && errors.email.type ==='maxLength' && <p className="text-danger">Email exceeds maximum length.</p> }
                { errors.email && errors.email.type ==='pattern' && <p className="text-danger">That is not a valid email.</p> }
            </div>
            <div className="form-group">
                <label for="password">Password</label>
                <input 
                  type="password" 
                  name="password" 
                  className={`form-control ${errors.password ? 'is-invalid' : ''}`}
                  id="password" 
                  placeholder="Password" 
                  ref={register({ required: true, minLength: 6 })}
                 />
                 { errors.password && errors.password.type ==='required' && <p className="text-danger">Password is required.</p> }
                 { errors.password && errors.password.type ==='minLength' && <p className="text-danger">Password is too short.</p> }
            </div>
            <button type="submit" className="btn btn-primary">Login</button>
            </form>

            <p>New User? <Link to={redirect ? `/register?redirect=${redirect}` : '/register' }>Register</Link></p>
        </>
    )
}

On the useEffect it says that container is not define and it won't let the toastr run.

Any idea how to fix this?

Firstly, I think your container ref isn't defined. You can use the useRef hook to define the container ref. Also, you forgot the title param when you call the success function: toastContainer.current.success(content, title, options);

import React, { useRef, useEffect } from "react";
import "./styles.css";
import { ToastContainer } from "react-toastr";

const LoginScreen = () => {
  let toastContainerRef = useRef();
  const userLogin = { success: "success" };
  const { success } = userLogin;

  useEffect(() => {
    // You will need to check if container.current exist. 
    if (toastContainerRef.current) {
      if (success) {
        toastContainerRef.current.success(`User successfully logged in!`, "title", {
          closeButton: true
        });
      }
    }
  }, [success]);

  return (
    <div className="container">
      <ToastContainer ref={toastContainerRef} className="toast" />
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM