React hook - onFocus and onBlur

Viewed 5037

I have changed the code from components to hooks. I'm completely new to it and i'm learning react and i need help to change it to hooks what should i do to make it work on functional react ?

  • update:
  • I have issued the solutions bellow but when i click on the input it takes me to the top of the page
  const [nameFocused, setNameFocused] = useState(true);
<FormGroup
                    className={classnames("mt-5", {
                      focused: nameFocused,
                    })}
                  >
                    <InputGroup className="input-group-alternative">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="ni ni-user-run" />
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input
                        placeholder="Your name"
                        type="text"
                        onFocus={(e) => setNameFocused(true)}
                        onBlur={(e) => setNameFocused(false)}
                      />
                    </InputGroup>
                  </FormGroup>

Not relevant:

<FormGroup
                    className={classnames("mt-5", {
                      focused: state.nameFocused,
                    })}
                  >
                    <InputGroup className="input-group-alternative">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="ni ni-user-run" />
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input
                            placeholder="Your name"
                            type="text"
                            onFocus={e => this.setState({ nameFocused: true })}
                            onBlur={e => this.setState({ nameFocused: false })}
                          />
                    </InputGroup>
                  </FormGroup>
``
3 Answers

You should use useState hook in your component.

Here nameFocused is a state and setNameFocused is equal to this.setState({ nameFocused: ...}) in class component.

import { useState } from 'react'

...
   const [nameFocused, setNameFocused] = useState(false)
              
   return (
    <FormGroup
      className={classnames("mt-5", {
        focused: nameFocused,
      })}
    >
      <InputGroup className="input-group-alternative">
        <InputGroupAddon addonType="prepend">
          <InputGroupText>
            <i className="ni ni-user-run" />
          </InputGroupText>
        </InputGroupAddon>
        <Input
              placeholder="Your name"
              type="text"
              onFocus={e => setNameFocused(true)}
              onBlur={e => setNameFocused(false)}
            />
      </InputGroup>
    </FormGroup>

   )
...

I'll just tell you how to handle state with hooks, read the docs and try and figure out the other hooks on your own.

This is how you handle state with hooks. First, "declare" the state variable:

const [nameFocused, setNameFocused] = useState(false)

You'll have to import { useState } from react first. The const [..] part is array destructuring. Look it up if you're not familiar. Basically, how this works is, the useState hook returns an array of two things, the first one is the default value to the state variable, and the second is a function to set the state variable. And the value you pass into the useState function is treated as the default value. In this case, it's false. So, after this line of code, we have the nameFocused variable with the value false and the setNameFocused function to set the value of the variable.

Like I already mentioned, the setNameFocused function can be used to the set the value of the state nameFocused. So your onBlur and onFocus handlers will look like:

...
  onBlur={() => setNameFocused(false)}
  onFocus={() => setNameFocused(true)}
...

One important thing to note is that the hooks should always to called in the same order, ie the hooks should never be called in an if block or anything similar.

import React,{useState} from "react"

1 change the class definition to a function definition and delete every this keyword.(command+shift+L) on vscode

let first_function = ()=>{...}

2 change the render() to return

3 group all your state into a single initial state variable[optional]

let initialState = {nameFocused:true || false}

4 Inside your functional component declare your states

let [state,setState] = useState(initialState)

5 when setting state with the useState hook

setState((previousState)=> ({...previousState, newState}))

example:

<Input
    placeholder="Your name"
    type="text"
    onFocus={e => setState((prev)=>({...prev, nameFocused: true }))}
    onBlur={e => setState((prev)=>({...prev, nameFocused: false }))}
  />

6 we have the useReducer hook , and with this you are free from the trouble of always keeping count of the previous state. react doc react hooks(useReducer)

Related