Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use useState in class component React.js

Tags:

reactjs

I am trying to create constants in react as follows:

const [firstFocus, setFirstFocus] = React.useState(false);
const [lastFocus, setLastFocus] = React.useState(false);

The constants are being used in the code as follows:

import React, { Component } from 'react'
import axios from 'axios'

import {
    Button,
    Card,
    CardHeader,
    CardBody,
    CardFooter,
    Form,
    Input,
    InputGroupAddon,
    InputGroupText,
    InputGroup,
    Container,
    Col
} from "reactstrap";

class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            email: '',
            password: ''
        }
    }

    changeHandler = (e) => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitHandler = (e) => {
        e.preventDefault()
        console.log(this.state)
        axios.post('https://jsonplaceholder.typicode.com/posts', this.state)
            .then(response => {
                console.log(response)
            })
            .catch(error => {
                console.log(error)
            })
    }


    render() {
        const { email, password } = this.state
        **const [firstFocus, setFirstFocus] = React.useState(false);
        const [lastFocus, setLastFocus] = React.useState(false);**
        return (

            <div>
                <Col className="ml-auto mr-auto" md="4">
                    <Card className="card-login card-plain">
                        <Form onSubmit={this.submitHandler} className="form">
                            <CardHeader className="text-center">
                            </CardHeader>
                            <CardBody>
                                <InputGroup
                                    className={
                                        "no-border input-lg"
                                    }
                                >
                                    <InputGroupAddon addonType="prepend">
                                        <InputGroupText>
                                            <i className="now-ui-icons ui-1_email-85"></i>
                                        </InputGroupText>
                                    </InputGroupAddon>
                                    <Input
                                        placeholder="Email"
                                        type="text"
                                        name="email"
                                        value={email}
                                        onChange={this.changeHandler}
                                    // onFocus={() => setFirstFocus(true)}
                                    // onBlur={() => setFirstFocus(false)}
                                    ></Input>
                                </InputGroup>
                                <InputGroup
                                    className={
                                        "no-border input-lg"
                                    }
                                >
                                    <InputGroupAddon addonType="prepend">
                                        <InputGroupText>
                                            <i className="now-ui-icons ui-1_lock-circle-open"></i>
                                        </InputGroupText>
                                    </InputGroupAddon>
                                    <Input
                                        placeholder="Password"
                                        type="password"
                                        name="password"
                                        value={password}
                                        onChange={this.changeHandler}
                                    // onFocus={() => setLastFocus(true)}
                                    // onBlur={() => setLastFocus(false)}
                                    ></Input>
                                </InputGroup>
                            </CardBody>
                            <CardFooter className="text-center">
                                <Button
                                    block
                                    className="btn-round"
                                    color="info"
                                    type="submit"
                                    size="lg"
                                >
                                    Get Started
                    </Button>
                                <div className="pull-right">
                                    <h6>
                                        <a
                                            className="link"
                                            href="#pablo"
                                            onClick={e => e.preventDefault()}
                                        >
                                            Need Help?
                        </a>
                                    </h6>
                                </div>
                            </CardFooter>
                        </Form>
                    </Card>
                </Col>
            </div>
        )
    }
}

export default PostForm

However, when I try to do this I get the following error:

Invalid hook call. Hooks can only be called inside of the body of a function component.

I created another constant there for email and password and it worked just fine so I'm not sure why my useState constants aren't working. Any help or guidance is much appreciated as I am very new to react. Thanks!

like image 667
youngdev Avatar asked Mar 31 '20 22:03

youngdev


People also ask

Can we use React useState in class component?

Hooks and Function Components You might have previously known these as “stateless components”. We're now introducing the ability to use React state from these, so we prefer the name “function components”. Hooks don't work inside classes. But you can use them instead of writing classes.

Can we use useState in class component?

useState takes just one argument which is the intial value, and returns a stateful value and a function to change it, we destructured it like this: const [state, setState] = useState(initialValue); To use it, simply we can use it like the class example.

How do you use useState hook in class component?

Alternative Way to Use Hooks in React Class Components We import the useState hook to create a number state variable, initialized to a number value. The child component is a Header class component. We pass down the number state variable, which we created using a hook. Then we display this value in the child component.

What can I use instead of useState in React?

An alternative to the useState Hook, useReducer helps you manage complex state logic in React applications. When combined with other Hooks like useContext , useReducer can be a good alternative to Redux, Recoil or MobX. In certain cases, it is an outright better option.


1 Answers

In react, we have 2 ways to build components: classes and functions.

DOCS

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Using the State Hook:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Equivalent Class Example:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
like image 166
Esther-I Avatar answered Oct 12 '22 13:10

Esther-I