Hello,
So I have a javascript snippet for one of my components in my index.html
It is for my contact form. The function gets the name of the element, the form, and shows an alert upon submission. My code is below.
In my Index.html
<script type="text/javascript">
document.getElementById('form').onsubmit = function () {
alert(Thanks for submitting. Have a great day!);
};
</script>
Hi @Liamgrossman, if your script is placed before the HTML it will not work as is unless you wrap it in an window on load event listener:
<script type="text/javascript">
window.addEventListener('load', function() {
var form = document.getElementById('form');
form.addEventListener('submit', function () {
alert('Thanks for submitting. Have a great day!');
});
});
</script>
Otherwise move your script below the form’s HTML.
In any case check the developer console for javascript errors.
I noticed for example that your alert is missing quotes for the text and that would be definitely throwing an error and making the script not work.
On top of what @James_Hibbard said, this just won’t work. You’re going to rerender the page if you try to use a vanilla HTML form submission, so your JS snippet will never know anything happened because it won’t get ran on the same page. You need to handle this in your component.
I’ve seen a few posts from you here recently on React. Can I ask what training material you’re using to learn?
@mawburn I’ve been using online tutorials and documentation provided by facebook/react. Anyways I’ve been asking questions about this because I was told by someone that you can’t use script tags in a react component, he said its because it conflicts with the dom. So I’ve been posting here for solutions. And to answer @James_Hibbard, there is no reason to handle it outside, I just previously thought it was impossible to have it inside my react component.
Anyways I’ve been asking questions about this because I was told by someone that you can’t use script tags in a react component, he said its because it conflicts with the dom.
Something like that, yeah.
I highly suggest going through an A to B course on React and getting a solid foundation in the core concepts. It looks like you’re mixing a lot of things together and might be missing some fundamentals of how a these component based SPA frameworks work. They work a little differently than traditional static or server rendered sites.
There is actually a page on this in the React Docs. The docs are really good, but you need some kind of foundation to build off of before jumping into them.