Reputation: 612
I have a website page build-in core JavaScript. I have to include my react Application component on submit of the form and access that value in my react application.
JavaScript Code
<form name="myForm" onsubmit="validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<div id="index_button_container" style="display: none;"></div>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
} else {
// myFunction()
var hell = document.getElementById("index_button_container");
hell.style.display = 'block'
}
}
</script>
ReactCode:- File Name:- cart_button.js
'use strict';
const e = React.createElement;
class CartButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#index_button_container');
ReactDOM.render(e(CartButton), domContainer);
I want to use the value entered in the form in my react file. Is there any way to do this?
Thanks in advance
Upvotes: 0
Views: 410
Reputation: 350
Revised Answer:
Store the React component in a variable. Then on form submission, you can force the component to rerender and get your new value.
JavaScript Code
<form name="myForm" onsubmit="event.preventDefault(); validateForm();">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<div id="index_button_container" style="display: none;"></div>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
} else {
// myFunction()
myComponent.forceUpdate();
var hell = document.getElementById("index_button_container");
hell.style.display = 'block'
}
}
</script>
ReactCode:- File Name:- cart_button.js
<script>
const e = React.createElement;
class CartButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like: ' + document.forms["myForm"]["fname"].value
);
}
}
const domContainer = document.querySelector('#index_button_container');
var myComponent = ReactDOM.render(e(CartButton), domContainer);
</script>
Upvotes: 1
Reputation: 174
You question is not really clear. Why are you mixing react and vanilla when one of the two can go independent?
React handles everything on its own, and Vanilla can do everything react does, why can't use one of the two?
Upvotes: 0