Getting has been blocked by CORS policy error - reactjs

The below spring boot code is for controller
#CrossOrigin(origins="*")
#RestController
#RequestMapping("/flights")
public class FlightController {
#Autowired
private FlightService flightService;
#GetMapping("/getall")
public List<FlightsDTO> customer(){
return flightService.getFlights();
}
#GetMapping("/get/{flightId}")
public FlightsDTO CustomerbyId(#PathVariable Integer flightId) {
return flightService.getFlight(flightId);
}
#PostMapping("/save")
public ResponseEntity<FlightsDTO> save(#Valid #RequestBody FlightsDTO prod) {
return new ResponseEntity<FlightsDTO>(flightService.createFlight(prod), HttpStatus.CREATED);
}
#GetMapping("/search")
public List<FlightsDTO> searchProduct(#RequestParam("query") String query){
return flightService.searchFlight(query);
}
#PatchMapping("/partialupdatesourceName/{flightId}/{sourceName}")
public ResponseEntity<FlightsDTO> partialUpdateFlightSource(#PathVariable Integer flightId,#PathVariable String sourceName){
return new ResponseEntity<>(flightService.partialupdateFlightSource(flightId, sourceName),HttpStatus.OK);
}
#PatchMapping("/partialupdatedestinationName/{flightId}/{destinationName}")
public ResponseEntity<FlightsDTO> partialUpdateFlightDestination(#PathVariable Integer flightId,#PathVariable String destinationName){
return new ResponseEntity<>(flightService.partialupdateFlightDestination(flightId, destinationName),HttpStatus.OK);
}
#PatchMapping("/partialupdateprice/{flightId}/{price}")
public ResponseEntity<FlightsDTO> partialUpdateFlightPrice(#PathVariable Integer flightId,#PathVariable Long price){
return new ResponseEntity<>(flightService.partialupdateFlightPrice(flightId, price),HttpStatus.OK);
}
}
The below is the react code
import React, {Component} from "react";
import {Card, Form, Button, Col, Row} from "react-bootstrap";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import {faSave, faPlusSquare, faUndo} from "#fortawesome/free-solid-svg-icons"
import axios from "axios";
export default class Flights extends Component {
constructor(props){
super(props);
this.state = this.initialState;
this.flightChange = this.flightChange.bind(this);
this.submitFlight = this.submitFlight.bind(this);
}
initialState = {
flightId:'', companyName:'', sourceName:'', destinationName:'', price:''
}
resetFlight = () => {
this.setState(() => this.initialState);
}
submitFlight = event =>{
event.preventDefault();
const flight = {
flightId: this.state.flightId,
companyName: this.state.companyName,
sourceName: this.state.sourceName,
destinationName: this.state.destinationName,
price: this.state.price
};
axios.post("http://localhost:9092/flights/save",flight)
.then(response => {
if(response.data != null){
this.setState(this.initialState);
alert("Flight Saved Successfully");
}
});
}
flightChange = event =>{
this.setState({
[event.target.name]:event.target.value
});
}
render(){
const {flightId, companyName, sourceName, destinationName, price} = this.state;
return(
<Card className={"border border-dark bg-dark text-white"}>
<Card.Header>
<FontAwesomeIcon icon={faPlusSquare}/> Add New Flight
</Card.Header>
<Form onReset={this.resetFlight} onSubmit={this.submitFlight} id="flightFormId">
<Card.Body>
<Row>
<Form.Group as={Col} controlId="formGridFIGHTID">
<Form.Label>Flight ID</Form.Label>
<Form.Control required autoComplete="off"
type = "test" name = "flightId"
value={flightId}
onChange={this.flightChange}
className={"bg-dark text-white"}
placeholder="Enter the Flight Id" />
</Form.Group>
</Row>
<Row>
<Form.Group as={Col} controlId="formGridCompanyName">
<Form.Label>Company Name</Form.Label>
<Form.Control required autoComplete="off"
type = "test" name = "companyName"
value={companyName}
onChange={this.flightChange}
className={"bg-dark text-white"}
placeholder="Enter the Company Name" />
</Form.Group>
</Row>
<Row>
<Form.Group as={Col} controlId="formGridSourceName">
<Form.Label>Source Name</Form.Label>
<Form.Control required autoComplete="off"
type = "test" name = "sourceName"
value={sourceName}
onChange={this.flightChange}
className={"bg-dark text-white"}
placeholder="Enter the Source Name" />
</Form.Group>
</Row>
<Row>
<Form.Group as={Col} controlId="formGridDestinationName">
<Form.Label>Destination Name</Form.Label>
<Form.Control required autoComplete="off"
type = "test" name = "destinationName"
value={destinationName}
onChange={this.flightChange}
className={"bg-dark text-white"}
placeholder="Enter the Destination Name" />
</Form.Group>
</Row>
<Row>
<Form.Group as={Col} controlId="formGridPrice">
<Form.Label>Price</Form.Label>
<Form.Control required autoComplete="off"
type = "test" name = "price"
value={price}
onChange={this.flightChange}
className={"bg-dark text-white"}
placeholder="Enter the Price" />
</Form.Group>
</Row>
</Card.Body>
<Card.Footer style={{"textAlign":"right"}}>
<Button size="sm" variant="success" type="submit">
<FontAwesomeIcon icon={faSave} /> Submit
</Button>
<Button size="sm" variant="info" type="reset">
<FontAwesomeIcon icon={faUndo} /> Reset
</Button>
</Card.Footer>
</Form>
</Card>
);
}
}
After Running the server and submitting the values console is showing this error
error message
I have tried multiple solutions like changed the Cross origin annotation from * to the http://localhost:3000 and also add webMVCConfig but found no luck.
How To resolve this issue? btw I have also given Security to the controller, maybe because of that I am facing this issue.

Related

Reactjs Modal Form Submission with MySql (axios & sequelize)

Good Day,
I have a header outline with both Login and Sign Up Modal. At the moment I am working on the Sign Up Modal where for now I can insert a new User but I want to display another Modal to confirm signup successful as well as close the Sign Up Modal. Also to display error messages via Modal. Here is the outline of my header Code so far. along with the Authentication Controller Class.
AUTHENTICATION CODE
import { Op } from 'sequelize'
import bcryptjs from 'bcryptjs'
import jwt from 'jsonwebtoken'
import UsersModel from "../models/users_model.js"
export const register = (request, response, next) => {
const name = request.body.name
const surname = request.body.surname
const salt = bcryptjs.genSaltSync(10)
const passcode = bcryptjs.hashSync(request.body.passcode, salt)
const username = request.body.username
const email = request.body.email
UsersModel.findOrCreate({
where: { [Op.or]: [ { username }, { email } ] },
defaults: { name, surname, username, email, passcode }
}).then((created) => {
if (!created) return response.status(404).json('User exists')
else return response.status(200).json(created)
}).catch((error) => {
return response.status(500).json(error)
})
}
HEADER CODE
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Modal, CloseButton, Form, Row, Col, FloatingLabel, ModalBody } from 'react-bootstrap'
import 'bootstrap/scss/bootstrap.scss'
import axios from 'axios'
import './Header.scss'
function LoginModal(modal) {
return (
<>
<Modal {...modal} size={'lg'} aria-labelledby={'contained-modal-title-vcenter'} centered>
<Modal.Header closeButton={CloseButton}>
<Modal.Title>Login Panel</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form action='/' method={'POST'}>
<Form.Group className='mb-3' controlId='formBasicEmail'>
<Row className='align-items-center'>
<Col xs={'auto'}>
<FloatingLabel controlId='floatingInput' label='Username' className='mb-3'>
<Form.Control type={'text'} name={'username'} placeholder={'Type Username'} id={'username'} />
</FloatingLabel>
</Col>
<Col xs={'auto'}>
<FloatingLabel controlId='floatingInput' label='Passcode' className='mb-3'>
<Form.Control type={'password'} name={'passcode'} placeholder={'Type Passcode'} id={'passcode'} />
</FloatingLabel>
</Col>
</Row>
</Form.Group>
<Button variant={'primary'} type={'submit'}>Submit</Button>
</Form>
</Modal.Body>
<Modal.Footer>
<Button onClick={modal.onHide}>Close</Button>
</Modal.Footer>
</Modal>
</>
)
}
function RegisterModal(modal) {
const [inputs, dataSet] = useState({
name: '',
surname: '',
username: '',
email: '',
passcode: ''
})
const [ error, setError] = useState(null)
const navigate = useNavigate()
const dataEntry = (event) => {
dataSet((previous) => ({...previous, [event.target.name]: event.target.value }))
}
const dataSubmit = async (event) => {
event.preventDefault()
try {
await axios.post('auth/register/', inputs)
navigate('/')
} catch (error) {
setError(error.response.data)
}
}
return (
<>
<Modal {...modal} size={'lg'} aria-labelledby={'contained-modal-title-vcenter'} centered>
<Modal.Header closeButton={CloseButton}>
<Modal.Title>Sign Up</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Row className='mb-3'>
<Form.Group as={Col} controlId='formGridName'>
<Form.Label>Name</Form.Label>
<Form.Control type={'text'} name={'name'} placeholder={'Type Name'} id={'name'} onChange={dataEntry} />
</Form.Group>
<Form.Group as={Col} controlId='formGridSurname'>
<Form.Label>Surname</Form.Label>
<Form.Control type={'text'} name={'surname'} placeholder={'Type Surname'} id={'surname'} onChange={dataEntry} />
</Form.Group>
</Row>
<Row className='mb-3'>
<Form.Group as={Col} controlId='formGridEmail'>
<Form.Label>Email</Form.Label>
<Form.Control type={'email'} name={'email'} placeholder={'Type Email'} onChange={dataEntry} />
</Form.Group>
<Form.Group as='mb-3' controlId='formGridUsername'>
<Form.Label>Username</Form.Label>
<Form.Control type={'text'} name={'username'} placeholder={'Enter Userame'} id={'username'} onChange={dataEntry} />
</Form.Group>
<Form.Group as='mb-3' controlId='formGridPasscode'>
<Form.Label>Passcode</Form.Label>
<Form.Control type={'password'} name={'passcode'} placeholder={'Enter Passcode'} id={'passcode'} onChange={dataEntry} />
</Form.Group>
<Form.Group as='mb-3' controlId='formGridConfirm'>
<Form.Label>Passcode</Form.Label>
<Form.Control type={'password'} name={'confirm'} placeholder={'Confirm Passcode'} id={'confirm'} />
</Form.Group>
</Row>
<Form.Group as='mb-3' controlId='formGridSubmit'>
<Button variant={'primary'} type={'submit'} onClick={dataSubmit} >Submit</Button>
</Form.Group>
<Modal>
<ModalBody>{error && {error} }</ModalBody>
</Modal>
</Form>
</Modal.Body>
<Modal.Footer>
<Button onClick={modal.onHide}>Close</Button>
</Modal.Footer>
</Modal>
</>
)
}
export default function Header() {
const [loginModal, setLoginModal] = useState(false)
const [registerModal, setRegisterModal] = useState(false)
return (
<>
<header className='main-header'>
<nav className='nav-content'>
<ul className='nav-content-list'>
<li className='nav-content-item'>
<Button variant='primary' onClick={() => setLoginModal(true)}>Login</Button>
</li>
<li className='nav-content-item'>
<Button variant='primary' onClick={() => setRegisterModal(true)}>Sign Up</Button>
</li>
</ul>
</nav>
</header>
<LoginModal show={loginModal} onHide={() => setLoginModal(false)} />
<RegisterModal show={registerModal} onHide={() => setRegisterModal(false)} />
</>
)
}

Issue with Gatsby Netlify Form not receiving Submissions

I got the Netlify form working and accepting submissions but once I started setting up AJAX according to https://docs.netlify.com/forms/setup/, I can't figure out why submissions aren't being received.
Things I've tried:
Removing Hidden "form-name" input
Removing Recaptcha
Running "gatsby clean"
Removing opening Form tag's method attribute (method: "POST")
Removing action attribute from the opening Form tag and setting it directly in handleSubmit:
.then(() => navigate("/thank-you/"))
Any suggestions or fixes are really appreciated!
contact-form.js:
import React, { setState } from "react"
import styled from "styled-components"
import Recaptcha from "react-google-recaptcha"
import { navigate } from "gatsby"
import { Button, Col, Form, Row } from "react-bootstrap"
import { breakpoints } from "../utils/breakpoints"
const RECAPTCHA_KEY = process.env.GATSBY_RECAPTCHA_KEY
export default function ContactForm() {
const [state, setState] = React.useState({})
const recaptchaRef = React.createRef() // new Ref for reCaptcha
const [buttonDisabled, setButtonDisabled] = React.useState(true)
const handleChange = e => {
setState({ ...state, [e.target.name]: e.target.value })
}
const encode = data => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&")
}
const handleSubmit = e => {
e.preventDefault()
const form = e.target
const recaptchaValue = recaptchaRef.current.getValue()
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": "contact",
"g-recaptcha-response": recaptchaValue,
...state,
}),
})
.then(() => navigate(form.getAttribute("action")))
.catch(error => alert(error))
}
return (
<Form
name="contact"
method="POST"
netlify
action="/thank-you"
netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
onSubmit={handleSubmit}
>
<Row>
<Col md={12}>
<h3>Message Us</h3>
</Col>
</Row>
<Row>
<Col md={6}>
<Form.Group hidden>
<Form.Label htmlFor="bot-field">
Bot Field: Humans do not fill out!
</Form.Label>
<Form.Control name="bot-field" />
<Form.Control name="form-name" value="contact" />
</Form.Group>
<Form.Group>
<Form.Label htmlFor="first-name">First Name</Form.Label>
<Form.Control
required
size="lg"
type="text"
name="first-name"
onChange={handleChange}
/>
</Form.Group>
</Col>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="last-name">Last Name</Form.Label>
<Form.Control
required
size="lg"
type="text"
name="last-name"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="email">Email</Form.Label>
<Form.Control
required
size="lg"
type="email"
name="email"
onChange={handleChange}
/>
</Form.Group>
</Col>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="phone">Phone (Optional)</Form.Label>
<Form.Control
size="lg"
type="tel"
name="phone"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={12}>
<Form.Group>
<Form.Label htmlFor="message">Message</Form.Label>
<Form.Control
required
as="textarea"
rows="3"
placeholder="Enter your message here."
name="message"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={12}>
<FormControls>
<Recaptcha
ref={recaptchaRef}
sitekey={RECAPTCHA_KEY}
size="normal"
id="recaptcha-google"
onChange={() => setButtonDisabled(false)} // disable the disabled button!
className="mb-3"
/>
<div>
<Button className="mr-3" type="reset" value="Eraser">
Clear
</Button>
<Button type="submit" disabled={buttonDisabled}>
Send
</Button>
</div>
</FormControls>
</Col>
</Row>
</Form>
)
}
const FormControls = styled.div`
display: flex;
align-items: center;
flex-direction: column;
#media ${breakpoints.sm} {
flex-direction: row;
justify-content: space-between;
}
button[disabled] {
cursor: not-allowed;
}
gatsby-config:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `...`,
description: `...`,
author: `...`,
},
flags: {
DEV_SSR: false,
},
plugins: [
`gatsby-plugin-gatsby-cloud`,
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-plugin-styled-components`,
`gatsby-plugin-typography`,
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`,
},
}
HTML File in Static Folder:
<form
data-netlify="true"
name="contactVivaz"
method="POST"
data-netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
>
<input type="text" name="first-name" />
<input type="text" name="last-name" />
<input type="email" name="email" />
<input type="tel" name="phone" />
<textarea name="message"></textarea>
<div data-netlify-recaptcha="true"></div>
</form>
Your state management looks good, what it's mandatory is to have (and to check) the input value of hidden fields that must match exactly the form name in the JSX as well as in the Netlify's dashboard. Assuming that everything is well named, as it seems, I believe your issue comes from the Form component, which should looks like:
<Form
name="contact"
method="POST"
action="/thank-you"
data-netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
data-netlify="true"
onSubmit={handleSubmit}
>
Note the data-netlify-honeypot and data-netlify value.
For adding the reCAPTCHA field, you have two options:
Allowing Netlify to handle all the related logic by adding simply an empty <div> like:
<div data-netlify-recaptcha="true"/>
Adding a custom reCAPTCHA (your case) what required to add the environment variables in your Netlify dashboard (prefixed with GATSBY_) and sending the response with the g-recaptcha-response field so your POST request needs to have that field as the docs suggest:
The Netlify servers will check the submissions from that form, and
accept them only if they include a valid g-recaptcha-response value.
Further references to base your setup:
https://www.gatsbyjs.com/docs/building-a-contact-form/
https://www.seancdavis.com/blog/how-to-use-netlify-forms-with-gatsby/
https://medium.com/#szpytfire/setting-up-netlify-forms-with-gatsby-and-react-5ee4f56a79dc

How to add edit button and function in react.js

i want to share this question. So, i have a form which is designed by react-bootstrap. And also use React Hooks and React Function Component. I have a form which is add new form and delete form but i don't do edit form.
This is a return statement
return(
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control ref = {firstname} type="text" placeholder="Name.." />
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control ref = {secondname} type="text" placeholder="Surname.." />
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control ref = {email} type="email" placeholder="E-Mail" />
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control ref = {comment} as="textarea" rows={3} placeholder = "Notes :)"/>
</Form.Group>
<Button className = "btn-lg" onClick={handleSubmit} variant="success" type="submit">Submit</Button>
</Form>
</Col>
</Row>
{Formss}
</Container>
)
And then, These are the function of this return
const Formss = input.map((item , index) =>
{
return(
<Lists key = {index} item = {item} index = {index} deleteFunc={handleDelete}/>
)
}
)
const handleSubmit = (event) => {
event.preventDefault();
const name = firstname.current.value
const surname = secondname.current.value
const mail = email.current.value
const mycomment = comment.current.value
const data = {id:id(),
name : name,
surname : surname,
mail : mail,
mycomment : mycomment}
if(data.name && data.surname && data.mail && data.mycomment){
setInput([...input, data])
firstname.current.value = ""
secondname.current.value = ""
email.current.value = ""
comment.current.value =""
}else{
console.log("oopss")
}
}
I use ref hook for handleSubmit. So, How to add edit button and edit function?
To be able to edit data, and to save it in state you can do it as in provided example. Then in handleSubmit function you can process your data further:
import React from "react";
import { Container, Row, Col, Form, Button } from "react-bootstrap";
const App = () => {
const handleSubmit = (e) => {
e.preventDefault();
console.log(state);
};
const initialState = {
firstname: "",
secondname: "",
email: "",
comment: "",
};
const [state, setState] = React.useState(initialState);
const handleChange = ({ target: { value, name } }) => {
setState({ ...state, [name]: value });
};
return (
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
name="firstname"
value={state.firstname}
type="text"
placeholder="Name.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control
name="secondname"
value={state.secondname}
type="text"
placeholder="Surname.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control
value={state.email}
name="email"
type="email"
placeholder="E-Mail"
onChange={handleChange}
/>
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control
name="comment"
value={state.comment}
as="textarea"
rows={3}
placeholder="Notes :)"
onChange={handleChange}
/>
</Form.Group>
<Button className="btn-lg" variant="success" type="submit">
Submit
</Button>
</Form>
</Col>
</Row>
</Container>
);
};
export default App;

Radio Buttons in React using Bootstrap always post same value

I am not getting an error, but the radio buttons I am writing are always sending the same value to the database, and I am not sure why or how to fix it.
UPDATE. I have attached the complete code. Hopefully this provides more detail. Everything is working but the radio buttons. Can someone shed some light as to how I can fix this?
import React from "react";
import axios from "axios";
import Form from 'react-bootstrap/Form'
import Row from 'react-bootstrap/Col'
import Button from 'react-bootstrap/Button'
import './Form.css'
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { tickets: [] };
this.firstName = React.createRef();
this.lastName = React.createRef();
this.email = React.createRef();
this.category = React.createRef();
this.content = React.createRef();
this.urgency = React.createRef();
}
componentDidMount() {
this.getData();
}
getData = () => {
// Java Spring Boot uses port 8080
let url = "http://localhost:8080/tickets";
// axios.get(url).then(response => console.log(response.data));
axios.get(url).then(response => this.setState({ tickets: response.data }));
};
addTicket = () => {
let url = "http://localhost:8080/tickets";
axios.post(url, {
firstName: this.firstName.current.value,
lastName: this.lastName.current.value,
email: this.email.current.value,
category: this.category.current.value,
content: this.content.current.value,
urgency: this.urgency.current.value
}).then(response => {
// refresh the data
this.getData();
// empty the input
this.firstName.current.value = "";
this.lastName.current.value = "";
this.email.current.value = "";
this.content.current.value = "";
});
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<Form.Group className="Input">
<Form.Control type="text" name="firstName" placeholder="First Name" ref={this.firstName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="lastName" placeholder="Last Name" ref={this.lastName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="email" placeholder="Email" ref={this.email} />
</Form.Group>
<br></br>
<Form.Group className="dropdown">
<Form.Label>Select a Category:</Form.Label>
<Form.Control as="select" ref={this.category}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</Form.Control>
</Form.Group>
<br></br>
<Form.Group className="Issue">
<Form.Label>Please Describe Your Issue:</Form.Label>
<Form.Control as="textarea" rows="7" ref={this.content} />
</Form.Group>
<fieldset>
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check className="radioButtons"
type="radio"
label="Urgent"
name="selectedOption"
value="Urgent"
ref={this.urgency}
/>
<Form.Check className="radioButtons"
type="radio"
label="Standard"
name="selectedOption"
value="Standard"
ref={this.urgency}
/>
<Form.Check className="radioButtons"
type="radio"
label="Low Priority"
name="selectedOption"
value="Low Priority"
ref={this.urgency}
/>
</Form.Group>
</fieldset>
<Button variant="secondary" type="button" className="submit" onClick={this.addTicket}>Submit Ticket</Button>
</form>
</div>
);
}
}
export default Home;
The issue is that you are pointing this.urgency to all of your Radio components 1 by 1. Here is a brief simulation of running your code from top to bottom:
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check
value="Urgent"
ref={this.urgency} // <-- this.urgency is now pointing to this 1st component
/>
<Form.Check
value="Standard"
ref={this.urgency} // <-- this.urgency is now pointing to this 2nd component
/>
<Form.Check
value="Low Priority"
ref={this.urgency} // <-- this.urgency is now pointing to this 3rd component
/>
</Form.Group>
So the final reference of this.urgency when the code is finished running is the 3rd component. So when you access this.urgency.current.value it will always return the 3rd component's value (i.e., Low Priority)
In React, you normally use state to hold these values - use ref sparsely and only if you really have to.
Here is an example of a solution:
constructor(props) {
super(props);
this.state = {
tickets: [],
urgency: "" // state for urgency
};
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check
value="Urgent"
onChange={() => this.setState({ urgency: "Urgent" })}
/>
<Form.Check
value="Standard"
onChange={() => this.setState({ urgency: "Standard" })}
/>
<Form.Check
value="Low Priority"
onChange={() => this.setState({ urgency: "Low Priority" })}
/>
</Form.Group>
axios
.post(url, {
urgency: this.state.urgency
})
you ref three elements to the same ref. you can walk around this without changing your login and adding state by helper function. in that way you don't change behavoir of your code (is not perferct ...) but you avoid rendering forced by setState.
import React from "react"
import Form from 'react-bootstrap/Form'
import Row from 'react-bootstrap/Col'
import Button from 'react-bootstrap/Button'
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { tickets: [] };
this.firstName = React.createRef();
this.lastName = React.createRef();
this.email = React.createRef();
this.category = React.createRef();
this.content = React.createRef();
this.urgency = React.createRef();
}
componentDidMount() {
}
getData = () => {
};
addTicket = () => {
console.log({
firstName: this.firstName.current.value,
lastName: this.lastName.current.value,
email: this.email.current.value,
category: this.category.current.value,
content: this.content.current.value,
urgency: this.urgency.current.value
})
};
handleCheckBoxChange(ref, event){
if(event.target.checked){
ref.current = {value: event.target.value}
}
}
render() {
return (
<div>
<form onSubmit={this.addTicket}>
<Form.Group className="Input">
<Form.Control type="text" name="firstName" placeholder="First Name" ref={this.firstName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="lastName" placeholder="Last Name" ref={this.lastName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="email" placeholder="Email" ref={this.email} />
</Form.Group>
<br></br>
<Form.Group className="dropdown">
<Form.Label>Select a Category:</Form.Label>
<Form.Control as="select" ref={this.category}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</Form.Control>
</Form.Group>
<br></br>
<Form.Group className="Issue">
<Form.Label>Please Describe Your Issue:</Form.Label>
<Form.Control as="textarea" rows="7" ref={this.content} />
</Form.Group>
<fieldset>
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check className="radioButtons"
type="radio"
label="Urgent"
name="selectedOption"
value="Urgent"
onClick={this.handleCheckBoxChange.bind(this, this.urgency)}
/>
<Form.Check className="radioButtons"
type="radio"
label="Standard"
name="selectedOption"
value="Standard"
onClick={this.handleCheckBoxChange.bind(this, this.urgency)}
/>
<Form.Check className="radioButtons"
type="radio"
label="Low Priority"
name="selectedOption"
value="Low Priority"
onClick={this.handleCheckBoxChange.bind(this, this.urgency)}
/>
</Form.Group>
</fieldset>
<Button variant="secondary" type="button" className="submit" onClick={this.addTicket}>Submit Ticket</Button>
</form>
</div>
);
}
}
export default Home;

Unexpected use of 'event' on Login

I'm running a react-create-app and it's giving me the following errors on my below Login.js
./src/components/Login/Login.js
Line 6: 'handleClick' is not defined no-undef
Line 6: Unexpected use of 'event' no-restricted-globals
I've tried moving the handleClick event elsewhere in the js file but I continue to get the same error.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {Button, Checkbox, Col, ControlLabel, Form, FormControl, FormGroup} from 'react-bootstrap';
import './Login.css';
handleClick(event)
{
const username = this.refs.username;
const password = this.refs.password;
const creds = { username: username.value.trim(), password: password.value.trim() };
this.props.onLoginClick(creds)
}
Login.propTypes = {
onLoginClick: PropTypes.func.isRequired,
errorMessage: PropTypes.string
};
class Login extends Component {
render() {
const { errorMessage } = this.props;
return (
<Form horizontal>
<FormGroup controlId="formHorizontalEmail">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl type="email" placeholder="Email" />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<FormControl type="password" placeholder="Password" />
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Checkbox>Remember me</Checkbox>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button onClick={(event) => this.handleClick(event)} type="submit">Sign in</Button>
</Col>
</FormGroup>
{errorMessage &&
<p style={{color:'red'}}>{errorMessage}</p>
}
</Form>
);
}
}
export default Login;
This ended up working:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {Button, Checkbox, Col, ControlLabel, Form, FormControl, FormGroup} from 'react-bootstrap';
import './Login.css';
class Login extends Component {
render() {
const { errorMessage } = this.props;
Login.propTypes = {
onLoginClick: PropTypes.func.isRequired,
errorMessage: PropTypes.string
}
function handleClick(event) {
const username = this.refs.username;
const password = this.refs.password;
const creds = { username: username.value.trim(), password: password.value.trim() };
this.props.onLoginClick(creds)
}
return (
<Form horizontal>
<FormGroup controlId="formHorizontalEmail">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl type="email" placeholder="Email" />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<FormControl type="password" placeholder="Password" />
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Checkbox>Remember me</Checkbox>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button onClick={(event) => handleClick(event)} type="submit">Sign in</Button>
</Col>
</FormGroup>
{errorMessage &&
<p style={{color:'red'}}>{errorMessage}</p>
}
</Form>
)
}
}
export default Login;
Moving handleClick inside the class fixes the error:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {Button, Checkbox, Col, ControlLabel, Form, FormControl, FormGroup} from 'react-bootstrap';
import './Login.css';
Login.propTypes = {
onLoginClick: PropTypes.func.isRequired,
errorMessage: PropTypes.string
};
class Login extends Component {
handleClick(event)
{
const username = this.refs.username;
const password = this.refs.password;
const creds = {
username: username.value.trim(),
password: password.value.trim()
};
this.props.onLoginClick(creds)
}
render() {
const { errorMessage } = this.props;
return (
<Form horizontal>
<FormGroup controlId="formHorizontalEmail">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl type="email" placeholder="Email" />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<FormControl type="password" placeholder="Password" />
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Checkbox>Remember me</Checkbox>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button onClick={(event) => this.handleClick(event)} type="submit">Sign in</Button>
</Col>
</FormGroup>
{errorMessage &&
<p style={{color:'red'}}>{errorMessage}</p>
}
</Form>
);
}
}
export default Login;

Resources