'Can’t write scripts in react
So, I’m making a website with react&remi.js , and everything is set up and ready to go just one thing, I can’t use javascript functions and stuff inside .jsx file anyone knows how?
i tried to put the script out of the “return” but it doesn’t get the function name, doesn’t do anything, here's how i did it..
export default function Index() {
return (
<div>
<div id="myNav" class="overlay">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="overlay-content">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
</div>
<h2>testing the nav</h2>
<span className="spanText" onclick={openNav}>☰ open</span>
</div>
);
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
}
Solution 1:[1]
To add on to what Tomas said:
- In react elements, it should be
className=
, notclass=
- In react, to invoke functions, you should use
onClick={/* your code */}
, using {} instead of "" - Also, be careful about invoking functions when declaring your element rather than at the time the event is run:
onClick={closeNav()}
will call closeNav when defining the react element, and then throw an error when you actually click on the element
onClick={closeNav}
will not invoke the function until you click on the element
onClick={() => closeNav()}
will also work
Here's code with all those changes applied:
export default function Index() {
return (
<div>
<div id="myNav" className="overlay">
<a href="javascript:void(0)" className="closebtn" onClick={closeNav}>
×
</a>
<div className="overlay-content">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
</div>
<h2>testing the nav</h2>
<span className="spanText" onClick={openNav}>
☰ open
</span>
</div>
);
function openNav() {
alert('open');
document.getElementById('myNav').style.width = '100%';
}
function closeNav() {
alert('close');
document.getElementById('myNav').style.width = '0%';
}
}
Here's a working sandbox with this code: https://codesandbox.io/s/react-scratchpad-forked-qtfb8x?file=/src/index.js
FWIW - the problems you're running into are all react related, remix isn't causing the issues here.
Solution 2:[2]
You can definitely use javascript
inside a JSX file.
Plus onclick
should be onClick
for the click event
export default function Index() {
const closeNav = () => { /... };
return (
<div className="closebtn" onClick="closeNav">×</div>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stephen Sisk |
Solution 2 |