Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UseState Hooks in react gatsby

Tags:

reactjs

gatsby

import React, {useState} from 'react'
import Layout from "../components/layout"

const blog = () => {
    const [state, setState] = useState({
        name: 'Kerry',
        age: 20
    });
    return (
        <Layout>
        <div>
            <h1>blog</h1>
            <p>Post will show up here later on</p>
            {state.name + state.age}
            
        </div>
        </Layout>
    )
}

export default blog

Hi I am trying to print out name from state. I am using react hooks. This project is built in gatsby command. From my understanding the line {state.name + state.age} should return my name and age.

but the programs terminal is returning rebuilding failed

Also The program is giving me 2 error.

here theses two

5:19  warning  'setState' is assigned a value but never used no-unused-vars

 5:31  error    React Hook "useState" is called in function "blog" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

So a, i using useState wrong

like image 858
Khant Avatar asked Oct 17 '25 07:10

Khant


1 Answers

Components must start with capital letters. You have to change blog to Blog. The rest of the code seems correct.

This is because if they start with a lowercase letter, it is interpreted as a built-in component such as <p> or <img> by React. Since they are passed to React.createElement it breaks your code.

You can check for further information in React's official documentation.

like image 102
Ferran Buireu Avatar answered Oct 19 '25 00:10

Ferran Buireu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!