I use react with links but useState
is not defined
<script src="@16/umd/react.production.min.js"></script>
<script src="@16/umd/react-dom.production.min.js"></script>
<script src="/[email protected]/babel.min.js"></script>
<script type="text/babel">
function App() {
const [name , setName] = useState('ali');
const handelClick = () => {
setName('mahdi')
}
return (
<div className="continer">
<header>
<Navbar />
</header>
<div className="test">
<div>{name}</div>
<button type="button" name="button" onClick={handelClick}> click </button>
</div>
<div className="content">
<Business />
</div>
</div>
)
}
//render ponents
ReactDOM.render(
<App />,
document.getElementById("root")
);
</script>
I use react with links but useState
is not defined
<script src="https://unpkg./react@16/umd/react.production.min.js"></script>
<script src="https://unpkg./react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg./[email protected]/babel.min.js"></script>
<script type="text/babel">
function App() {
const [name , setName] = useState('ali');
const handelClick = () => {
setName('mahdi')
}
return (
<div className="continer">
<header>
<Navbar />
</header>
<div className="test">
<div>{name}</div>
<button type="button" name="button" onClick={handelClick}> click </button>
</div>
<div className="content">
<Business />
</div>
</div>
)
}
//render ponents
ReactDOM.render(
<App />,
document.getElementById("root")
);
</script>
Share
Improve this question
asked Apr 24, 2021 at 16:50
Ali RahmaniAli Rahmani
511 silver badge4 bronze badges
3
- 2 First you have to import it : "import {useState} from "react" – klaus_bathory Commented Apr 24, 2021 at 16:53
-
1
You have to use it from the
React
object, usually by destructuring at the top of your code:const { useState } = React;
– T.J. Crowder Commented Apr 24, 2021 at 16:53 - 1 @klaus_bathory - Given the content of the script tags above, they don't appear to be using modules. – T.J. Crowder Commented Apr 24, 2021 at 16:54
3 Answers
Reset to default 7You need to take it from the global React object.
const { useState } = React;
function App() {
// ...
Same sort of thing for all other hooks.
You also might want to change handelClick
to handleClick
to avoid confusing yourself.
since you use CDN, you must use it as property of object React
like this:
//...
const [name , setName] = React.useState('ali');
//...
If you encountered this problem trying to create a code snippet in StackOverflow like I did then part of the problem is that the latest version in the dropdown at the time of writing is 16.6.3.
The hooks were added in 16.6.1 but they were behind a feature flag and not enabled by default until 16.8.0.
So using:
const { useState } = React;
or:
React.useState(...)
alone will not solve the problem.
Make sure to also use a version >= 16.8.0.