I was trying React without the NPM and other tools and instead using it by adding the CDN links, but how to import the dependant packages, for example the useState hook? If it is added via another script tag, what is the CDN link for the same? below is my code,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>React Local</title>
<script type="application/javascript" src="https://unpkg.com/react@16.0.0/umd/react.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const rootElement = document.getElementById('root')
const App = (props) => {
const [text, setText] = useState('hello');
return (
<div>
<h1>{text}</h1>
<input type="text" onClick={(e) => setText(e.target.value)}> </input>
</div>
);
}
ReactDOM.render(<App />, rootElement)
</script>
</body>
</html>
Here I will get error, useState is not defined.
Note: This is just to test the React using the scripts from the CDN directly added in the html file, though i am aware of the create-react-app and the modern tools
When you use scripts, React is exposed on the window object as React
, you also use a version of React which doesn't have hooks(hooks were released in 16.8)
Update your scripts to(you might want to use the development scripts for better error messages)
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
If you want to access useState
destructure it from React
or use React.useState
Also, use onChange
instead of onClick
for input change events as well as using the text
value from state as the value
of the input
<script type="text/babel">
const { useState } = React
const App = (props) => {
const [text, setText] = useState('hello');
return (
<div>
<h1>{text}</h1>
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
</div>
);
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
</script>