Friday, October 4, 2019

useRef

useRef is a way to grab a handle of a DOM object and manipulate it for various purposes.

There are many uses for this hook. All the way from validation, styling to more trivial things like set focus on controls, gather data from a form....etc. Let's start with a handle to a control and set focus to it when page loads.

import React, {useRef, useState, useEffect} from 'react'

const Login = () => {
    const emailInputRef = useRef();
    const [loginForm, setLoginForm] = useState({email:'', password: ''});
    useEffect(() => {
      emailInputRef.current.focus();
    }, [])
    return (
        <div
      className="row flex-row justify-content-center align-items-center"
      style={{ marginTop: "80px", marginBottom: "30px" }}
    >
      <div className="col-lg-4 ">
        <div className="bs-component">
          <form onSubmit={(e) => { e.preventDefault(); console.log(loginForm); }}>
            <fieldset>
              <legend>Player Login</legend>
              <div className="form-group">
                <label htmlFor="exampleInputEmail1">Email address</label>
                <input
                  type="email"
                  className="form-control"
                  id="exampleInputEmail1"
                  aria-describedby="emailHelp"
                  placeholder="Enter email"
                  ref={emailInputRef}
                  value={loginForm.email}
                  onChange={e=>{
                    setLoginForm({email: e.target.value});
                  }}
                />
                <small id="emailHelp" className="form-text text-muted">
                  EMail ID you registerd with
                </small>
              </div>
              <button type="submit" className="btn btn-primary">
                Submit
              </button>
            </fieldset>
          </form>
        </div>
      </div>
    </div>
    )
}

export default Login;

This can be extended more to other cases like say for example, we want to extract  data from inputref, we can do that easily

const onSubmit = (e) => {
  e.preventDefault();
  const email = emailInputRef.current.value
  const password = passwordINputRef.current.value
  // Now submit data to login
  // Redirect user
}

There are few other simple cases useRef will be super helpful for things like Scroll-Spy, tabs etc

No comments: