Reputation: 3226
I am trying to create a component based on this article:
But simply copy pasting the functional component from the above link throws an error:
TypeError: Object(...) is not a function
Home
src/components/Home.js:3
1 | import React, { useState, useEffect } from 'react';
2 |
> 3 | function Home() {
4 |
5 | const [userName, setUsername] = useState('JD');
6 | const [firstName, setFirstname] = useState('John');
Full component code:
import React, { useState, useEffect } from 'react';
function Home() {
const [userName, setUsername] = useState('JD');
const [firstName, setFirstname] = useState('John');
const [lastName, setLastname] = useState('Doe');
useEffect(() => {
setInterval(() => {
setUsername('MJ');
setFirstname('Mary');
setLastname('Jane');
}, 5000);
});
const logName = () => {
// do whatever with the names ...
console.log(this.state.userName);
console.log(this.state.firstName);
console.log(this.state.lastName);
};
const handleUserNameInput = e => {
setUsername({ userName: e.target.value });
};
const handleFirstNameInput = e => {
setFirstname({ firstName: e.target.value });
};
const handleLastNameInput = e => {
setLastname({ lastName: e.target.value });
};
return (
<div>
<h3> The text fields will update in 5 seconds </h3>
<input
type="text"
onChange={handleUserNameInput}
value={userName}
placeholder="Your username"
/>
<input
type="text"
onChange={handleFirstNameInput}
value={firstName}
placeholder="Your firstname"
/>
<input
type="text"
onChange={handleLastNameInput}
value={lastName}
placeholder="Your lastname"
/>
<button className="btn btn-large right" onClick={logName}>
{' '}
Log Names{' '}
</button>
</div>
);
};
export default Home;
Upvotes: 2
Views: 2284
Reputation: 491
Hooks are an upcoming feature that lets you use state and other React features without writing a class. They’re currently in React v16.8.0-alpha.0.
Please check react version as the hook methods works with v16.8.0 .
Hope this helps,
Cheers !!
Upvotes: 5