How to send data from Modal, Form using react and bootstrap? - javascript

I am working with React to POST data in my local database. When I use just the <form>, it works fine. But whenever I am trying to use Modal and Bootstrap, it is giving me an error. I understand that my handleChange/handleSubmit is probably not assigning the values. Just wondering how to send the data from Modal to the handleChange.
Here is my code:
constructor(props) {
super(props);
this.state = {
institutionName: {},
institutionAddress: {},
institutionPhone: {},
allData: [],
};
this.onSubmit = this.handleSubmit.bind(this);
}
// this will look at the API and save the incoming data in allData variable
componentDidMount() {
fetch("/manageInstitution")
.then((res) => res.json())
.then((data) => this.setState({ allData: data }))
.then(console.log(this.state.allData));
}
// this is when submit button is pressed and data will be sent to database using api
handleSubmit(event) {
event.preventDefault();
const data = {
institutionName: this.state.institutionName,
institutionAddress: this.state.institutionAddress,
institutionPhone: this.state.institutionPhone,
};
fetch("/manageInstitution", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.catch((error) => console.error("Error: ", error))
.then((response) => console.log("Success: ", response));
window.location.reload(false);
}
// when a field changes in the form, do assignment to the state
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value.trim(),
});
};
handleModalShowHide() {
this.setState({ showHide: !this.state.showHide });
}
render() {
const { allData } = this.state;
return (
<div className="body">
<h4>Super Admin View</h4>
<div>
<Button variant="primary" onClick={() => this.handleModalShowHide()}>
Add New Institution
</Button>
<Modal
aria-labelledby="contained-modal-title-vcenter"
show={this.state.showHide}
onSubmit={this.handleSubmit}
>
<Modal.Header
closeButton
onClick={() => this.handleModalShowHide()}
>
<Modal.Title id="contained-modal-title-vcenter">
<h5>Add New Institution</h5>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form className="col-lg-6 offset-lg-3">
<Form.Group className="mb-3">
<Form.Label htmlFor="institutionName">
Institution Name:
</Form.Label>
<Form.Control
type="text"
size="sm"
name="institutionName"
placeholder="Enter Institution Name"
onChange={this.handleChange}
required
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label htmlFor="institutionAddress">
Institution Address:
</Form.Label>
<Form.Control
type="text"
size="sm"
name="institutionAddress"
placeholder="Enter Institution Address"
onChange={this.handleChange}
required
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label htmlFor="institutionPhone">
Institution Phone:
</Form.Label>
<Form.Control
type="tel"
size="sm"
name="institutionPhone"
placeholder="i.e 01911223344"
onChange={this.handleChange}
pattern="[0-9]{3}"
required
/>
</Form.Group>
</Form>
<Modal.Footer>
<Button
variant="secondary"
onClick={() => this.handleModalShowHide()} >Close </Button>
{" "}
<Button
className="btn btn-primary"
type="submit"
onClick={this.handleSubmit}>Submit</Button>
</Modal.Footer>
</Modal.Body>
</Modal>
</div>
);
}
}
export default addNewInstitution;
Here is the error:
TypeError: Cannot read properties of undefined (reading 'state')
handleSubmit
D:/eduBD-React/eduBD/client/src/components/superadmin/manageInstitution.jsx:30
27 | event.preventDefault();
28 |
29 | const data = {
> 30 | institutionName: this.state.institutionName,
31 | institutionAddress: this.state.institutionAddress,
32 | institutionPhone: this.state.institutionPhone,
33 | };

You need to bind or use an Arrow function to have this to point to
correct reference refer docs here
class App extends React.Component {
state = {
name: "hello"
};
handleChangeWithArrow = () => { // use this way to avoid such errors
console.log(this.state.name);
this.setState({ name: "helloo Im changed" });
};
handleChange() {
// need to bind this to work or use an arrow function
console.log(this.state.name);
this.setState({ name: "helloo Im changed" });
}
render() {
return (
<div>
<button onClick={this.handleChange}>Error Produced on Click</button>
<button onClick={this.handleChangeWithArrow}>
Click Me to change Name
</button>
{this.state.name}
</div>
);
}
}
ReactDOM.render(<App/>,document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related

Testing React hook from and yup validation using jest and enzyme

I am trying to test this form component(I have used react-bootstrap for UI).
const validationSchema =
Yup.object().shape({
username: Yup.string().required(),
password: Yup.string().required(),
})
const formOptions = { resolver: yupResolver(validationSchema) };
// get functions to build form with useForm() hook
const { register, handleSubmit, reset, formState } = useForm(formOptions);
const { errors } = formState;
function onSubmit(data) {
console.log(JSON.stringify(data));
return (
<div
data-test="reg-login-component"
className="bg-dark pt-4"
style={{ height: "100vh" }}
>
<Card style={{ width: "50vw", margin: "auto" }}>
<Card.Body>
<Card.Title>Login</Card.Title>
<Form noValidate onSubmit={handleSubmit(onSubmit)}>
<Form.Row>
<Form.Group as={Col} md="12" sm="12" xs="12">
<Form.Label>UserName</Form.Label>
<Form.Control
name="username"
type="text"
{...register("username")}
/>
<Card.Subtitle className="mb-2 text-danger mt-0">
{" "}
{errors.username?.message}
</Card.Subtitle>
</Form.Group>
</Form.Row>
<Container fluid className="pr-0 pl-0">
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Password</Form.Label>
<Form.Control
name="password"
type="password"
{...register("password")}
/>
<Card.Subtitle className="mb-2 text-danger mt-0">
{" "}
{errors.password?.message}
</Card.Subtitle>
</Form.Group>
</Form.Row>
</Container>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Card.Body>
</Card>
</div>
)};
Registration.test.js
Enzyme.configure({ adapter: new EnzymeAdapter() });
const setup = ()=> {
return mount(<Registration />);
};
describe("Checking valid inputs", () => {
it("submits input values", async () => {
const onSubmit = jest.fn();
const handleUserData = jest.fn();
const rendered = setup();
await act(async () => {
rendered
.find('input[name="username"]')
.simulate("input", { value: "harshitsankhala" })
.simulate("blur");
});
await act(async () => {
rendered.find("form").simulate("submit");
});
expect(onSubmit).toHaveBeenLastCalledWith(
expect.objectContaining({
username: "harshitsankhala",
})
);
});
});
when running npm test
getting this error ->
Checking valid inputs
× submits input values (81 ms)
● Checking valid inputs › submits input values
expect(jest.fn()).toHaveBeenLastCalledWith(...expected)
Expected: ObjectContaining {"username": "harshitsankhala"}
Number of calls: 0
58 | });
59 |
> 60 | expect(onSubmit).toHaveBeenLastCalledWith(
| ^
61 | expect.objectContaining({
62 | username: "harshitsankhala",
63 | })
i have used this code as a refrence for testing ->https://codesandbox.io/s/react-hook-form-enzyme-testing-example-5tn7i?from-embed=&file=/src/tests/app.test.js
How to resolve this issue??
or
How to perform test for react-hook-form and yup validation using enzyme and jest

handleSubmit with Formik using TypeScript

I have successfully written a Login component in React using plain Javascript. I would now like to convert this component to TypeScript. I have defined some types and also threw in some "any" just to initially compile. Unfortunately, the onClick parameter in my submit button throws the following error:
TS2322: Type '(e?: FormEvent | undefined) => void' is not assignable to type '(event: MouseEvent<HTMLElement, MouseEvent>)
=> void'.
Here is the relevant code:
class Login extends React.Component<LoginProps, LoginState> {
constructor(props) {
super(props);
this.login = this.login.bind(this);
}
async login(values) {
const user = {
email: values.email,
password: values.password,
};
const query = `mutation userLogin(
$user: UserLoginInputs!
) {
userLogin(
user: $user
) {
token
}
}`;
const data: any = await graphQLFetch(query, { user });
if (data && data.userLogin.token) {
const decoded: any = jwt.decode(data.userLogin.token);
const { onUserChange } = this.props;
onUserChange({ loggedIn: true, givenName: decoded.givenName });
const { history } = this.props;
history.push('/');
}
}
render() {
return (
<Formik
onSubmit={this.login}
validationSchema={loginSchema}
initialValues={{
email: '',
password: '',
}}
>
{({
handleSubmit,
handleChange,
values,
}) => (
<Card>
<Card.Body>
<Form>
<Form.Group>
<Form.Label>E-mail</Form.Label>
<Form.Control
name="email"
value={values.email}
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control
name="password"
value={values.password}
onChange={handleChange}
/>
</Form.Group>
</Form>
<Button
type="button"
variant="primary"
onClick={handleSubmit}
>
Submit
</Button>
</Card.Body>
</Card>
)}
</Formik>
);
}
}
I'm new to TypeScript and don't fully understand why an error occurs regarding e versus event when the login function does not explicitly reference either of those. Can someone please help me assign types to my handleSubmit function (aka login)?
I hope that example could help you to resolve your issue
import { Field, Form, Formik } from 'formik';
import * as React from 'react';
import './style.css';
interface MyFormValues {
firstName: string;
}
export default function App() {
const initialValues: MyFormValues = { firstName: '' };
const getSubmitHandler =
() =>
(values, formik) => {
console.log({ values, formik });
alert(JSON.stringify(values, null, 2));
formik.setSubmitting(false);
};
return (
<div>
<Formik
initialValues={initialValues}
onSubmit={getSubmitHandler()}
>
{(formik) => (
<Form>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="First Name" />
<button
type="button"
onClick={(event) =>
getSubmitHandler()(formik.values, formik)
}
>
Submit
</button>
</Form>
)}
</Formik>
</div>
);
}

sending info from react-select into a handleSubmit function

I receive some info from an API and show them as react-select drop-down items. I want to choose any item and then delete it by pressing a button, which sends the value to my handleSubmit function to be sent to the API again:
export class DeleteDepModal extends Component {
state = {
departments: [],
idValue: ' '
}
getDepartments() {
axios.get('/api/jobs/list-departments',{headers:headers}).then(resp=>{
this.setState({
departments: resp.data.map(departments=>({label:[departments.name,' ',departments.company_name], value:departments.id})),
})
})
}
componentDidMount() {
this.getDepartments()
}
handleSubmit = (event) => {
event.preventDefault()
console.log('handleDeletesubmitshot')
const DepID = this.state.idValue
axios(
{
method: 'delete',
url: '/api/jobs/delete-department' + DepID,
headers: headers,
})
.then(response => {
console.log(response)
alert('Department Deleted Successfully!')
})
.then(
this.getDepartments()
)
.catch(error => {
console.log(error.response)
})
}
render () {
return (
<Modal
{...this.props}
size='lg'
aria-labelledby='contained-modal-title-vcenter'
centered
>
<Modal.Header closeButton>
<Modal.Title style={{ color: 'black' }} id='contained-modal-title-vcenter'>
Delete Department
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className='container'>
<Form onSubmit={this.handleSubmit}>
{
<Row>
<Col xs={6}>
<Select onChange={(event) => this.setState({ idValue: event.target.departments[i].value})} placeholder='Select from pre-created Departments' required options={this.state.departments}/>
</Col>
<Col xs={6}>
<Button style={{ position: 'relative', left: '150px' }} variant='danger' type='submit'>Delete Department</Button>
</Col>
</Row>
}
</Form>
</div>
</Modal.Body>
<Modal.Footer />
</Modal>
)
}
}
departments[i].value is the info I want to send to my handleSubmit function, but now I have 2 problems:
I don't know how to iterate in my department's array and get the index of the item that is selected (i), a for loop doesn't work
event.target is unidentified and doesn't get the info to the handleSubmit function
What should I do?
With react select's onChange, you will get the value in the callback (not event). Also you don't need to iterate department array and get the index.
Below code should suffice
<Select
onChange={(value) =>
this.setState({
idValue: value,
})
}
placeholder="Select from pre-created Departments"
required
options={this.state.departments}
/>

React conditional rendering based on login logout and form submit

I am trying to initiate conditional rendering based on a form submit that goes to my node router but I am not getting the result. The buttons do not hide the content "ReminderModel" & "Reminder Table" and nothing happens when I submit the login form. I know this isnt the best way to do it but fi someone could point me in the right direction I would appreciate it. I would prefer not to use another plugin for react and would prefer to do it on my own to avoid update conflicts, etc.
import React, { Component } from 'react';
import { Container, Button, Form, Col } from 'react-bootstrap';
import axios from 'axios';
import './App.css';
import ReminderTable from './components/reminderList';
import ReminderModal from './components/modal';
const redColor = {
color: '#e52d2d'
}
class App extends Component {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.LoginButton = this.LoginButton.bind(this);
this.UponLoggedIn = this.UponLoggedIn.bind(this);
this.NotLoggedIn = this.NotLoggedIn.bind(this);
this.state = {
user:[],
isLoggedIn:false,
username:'',
password:''
};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
LoginButton = props => {
return(
<>
<div id="status"></div>
<Form
className="loginForm"
>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
name="username"
id="username"
value={this.state.value}
onChange={this.handleChange}
>
</Form.Control>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
id="password"
name="password"
value={this.state.value}
onChange={this.handleChange}
/>
</Form.Group>
</Form.Row>
<Button className="btn btn-sm btn-light" onClick={this.onSubmit}>
<i style={redColor} className="fas fa-sign-in-alt"></i> Login
</Button>
</Form>
</>
);
}
LogoutButton = props => {
return(
<>
<Button className="btn btn-sm btn-light float-right" onClick={this.NotLoggedIn}>
<i style={redColor} className="fas fa-sign-out-alt"></i> Logout
</Button>
</>
)
}
NotLoggedIn = props => {
return(
<>
<h4 className="text-muted"> Please Log in</h4>
{this.LoginButton()}
</>
)
}
UponLoggedIn = props => {
return(
<>
<ReminderModal />
<p className="text-muted text-center">If new reminder does not show up immediently please refresh page</p>
<ReminderTable />
</>
)
}
ViewScreen = props => {
const isLoggedIn = props.isLoggedIn;
if(isLoggedIn){
return this.UponLoggedIn();
}else {
return this.NotLoggedIn();
}
}
onSubmit = (e) => {
e.preventDefault();
axios.get('api/user')
.then(res => {
const user = res.data[0].username;
const password = res.data[0].password;
const username = this.state.username;
const passwordEntered = this.state.password;
if(user === username && passwordEntered === password){
if(username === '' && passwordEntered === ''){
document.getElementById('status').innerHTML = '<p>Please Enter A Valid Username and Password</p>';
this.NotLoggedIn();
}else{
document.getElementById('status').innerHTML = '<p>Please Enter A Valid Username and Password</p>';
this.NotLoggedIn();
}
this.UponLoggedIn();
}else {
this.NotLoggedIn();
}
})
.catch(error => {
console.log(error);
});
}
render(){
const isLoggedIn = this.state.isLoggedIn;
let button;
if (isLoggedIn) {
button = this.LoginButton();
} else {
button = this.LogoutButton();
}
return (
<div className="App container">
<h4
className="display-4 mt-4 mb-4 text-center"
>
<i style={redColor}
className="fas fa-asterisk">
</i> Expiration Reminder
</h4>
<Container isLoggedIn={isLoggedIn}>{button}</Container>
</div>
);
}
}
export default App;
You are calling this.NotLoggedIn in onClick handler, which is wrong, because NotLoggedIn returns React component. In the onCLick handler, you need to change state. So you should call this.handleLoginClick and this.handleLogoutClick instead.
Also there are couple of bugs. E.g. you are calling button = this.LoginButton(), but LoginButton functions expects props. You either have to pass the props to the function or you can access it in function as this.props.
Also the way you did it is kind of antipattern, because you are defining multiple components inside App component (LogoutButton, LoginButton etc.). You should split them into multiple classes.
I solved this in a fairly simple way, keep in mind I have a back end with express that searches a predefined username and pass that is why I used axios to fetch that info and check against it in the onSubmit function.
FYI: if you're feeling lost with React or any language really just start by doing projects, that is how I am learning, I took a few Udemy courses but still didn't grasp it, I learned by doing and with each project(big or small) you pick up something new and/or gain a better understanding along the way. Just a little food for thought if you're like me and have a passion but don't know where or how to start.
class App extends Component {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
user:[],
isLoggedIn:false,
username:'',
password:''
};
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleLogoutClick = e => {
this.setState({ isLoggedIn: false })
}
onSubmit = (e) => {
e.preventDefault();
axios.get('API_PATH')
.then(res => {
const user = res.data[0].username;
const password = res.data[0].password;
const username = this.state.username;
const passwordEntered = this.state.password;
if(user === username && passwordEntered === password){
this.setState({ isLoggedIn:true })
}
})
.catch(error => {
console.log(error);
});
}
render(){
return (
<div className="App">
<h4
className="display-4 mt-4 mb-4 text-center"
>
<i style={redColor}
className="fas fa-asterisk">
</i> Expiration Reminder
</h4>
<Container onSubmit={this.onSubmit}>
{this.state.isLoggedIn ? (
<>
<Button className="btn btn-sm btn-light mr-5 float-right" onClick={this.handleLogoutClick}>
<i style={redColor} className="fas fa-sign-out-alt"></i> Logout
</Button>
<ReminderModal />
<p className="text-muted text-center">If new reminder does not show up immediently please refresh page</p>
<ReminderTable />
</>
) : (
<>
<div id="status"></div>
<Form className="loginForm ml-5">
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
name="username"
id="username"
value={this.state.value}
onChange={this.handleChange}
>
</Form.Control>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
id="password"
name="password"
value={this.state.value}
onChange={this.handleChange}
/>
</Form.Group>
</Form.Row>
<Button className="btn btn-sm btn-light" onClick={this.onSubmit}>
<i style={redColor} className="fas fa-sign-in-alt"></i> Login
</Button>
</Form>
</>
)}
</Container>
</div>
)
}
}
export default App;

How to pass input from React Form to Axios get request and display the request result?

I am trying to take input from a user and pass that input into an axios get, when this is done the resultant information is passed into an array that will be displayed as cards.
I am having an issue where the code below is compiling but when enter values into the form fields and press submit, nothing occurrs. Nothing shows up in the web console either.
Where abouts am I going wrong?
const initial_state = {
location: "",
cuisine: "",
searchResults: []
};
class SearchMealForm extends Component {
constructor(props) {
super(props);
this.state = { ...initial_state };
}
//handle user input and inject it into yelp api get request
handleSubmit = event => {
event.preventDefault();
const { location, cuisine, searchResults} = this.state;
this.props.onFormSubmit(this.state(location, cuisine, searchResults));
axios.get(`https://api.yelp.com/v3/businesses/search?location=${location}+IE&categories=${cuisine}`)
.then(response => this.setState({searchResults}))
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
//YELP http api get request
searchYelpRestaurants = (location, cuisine, searchResults) => {
axios
.get(
`https://api.yelp.com/v3/businesses/search?location=${location}+IE&categories=${cuisine}`,
{
headers: {
Authorization: `Bearer ${process.env.REACT_APP_API_KEY_YELP}`
}
}
)
.then(res => this.setState({ searchResults: res.data.businesses }));
};
render() {
const { location, cuisine } = this.state;
//create cards with the results from the Yelp API GET
const YelpSearchResults = this.state.searchResults.map(result => {
return (
<div className="ResultCard">
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src={result.image_url} />
<Card.Body>
<Card.Title>{result.name}</Card.Title>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroupItem>{result.categories}</ListGroupItem>
<ListGroupItem>{result.rating}</ListGroupItem>
</ListGroup>
<Button variant="primary">Book restaurant</Button>
</Card>
</div>
);
});
// return YelpSearchResults;
// }
return (
<React.Fragment>
<div className="SearchMeal">
<Form onSubmit={this.handleSubmit}>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>City</Form.Label>
<Form.Control
name="location"
type="text"
value={location}
onChange={this.handleChange}
placeholder="location"
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Cuisine</Form.Label>
<Form.Control
name="cuisine"
type="text"
value={cuisine}
onChange={this.handleChange}
placeholder="cuisine"
/>
</Form.Group>
</Form.Row>
<Button>Submit</Button>
<Button>Clear</Button>
</Form>
</div>
{YelpSearchResults}
</React.Fragment>
);
}
}
export default SearchMealForm;
here Button type should be specified as submit
<Button type="submit">Submit</Button>
in order for form submit to work!
I would refactor your component to be functional
import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import {
Col,
Form,
Card,
Button,
ListGroup,
ListGroupItem
} from "react-bootstrap";
const initial_state = {
location: "",
cuisine: "",
searchResults: []
};
const SearchMealForm = ({ onFormSubmit = () => {} }) => {
const [state, setState] = useState(initial_state);
//handle user input and inject it into yelp api get request
const handleSubmit = async event => {
event.preventDefault();
const { location, cuisine } = state;
onFormSubmit(state);
const searchResults = await searchYelpRestaurants({ location, cuisine });
setState({ ...state, searchResults });
};
const handleChange = event => {
setState({
...state,
[event.target.name]: event.target.value
});
};
//YELP http api get request
const searchYelpRestaurants = async ({ location, cuisine }) => {
try {
const { data: { businesses: searchResults } = {} } = await axios.get(
`https://api.yelp.com/v3/businesses/search?location=${location}+IE&categories=${cuisine}`,
{
headers: {
Authorization: `Bearer dBMqyRFmBBg7DMZPK9v3rbGHmrLtlURpNUCJP6gbYHtyHTmboF-Mka-ZkHiDNq-G9ktATohJGD5iKQvelOHg3sDorBDiMgnsaa8SzTH8w6hjGQXlaIexDxFlTW3FXXYx`
}
}
);
return searchResults;
} catch (err) {
console.error(err);
}
return [];
};
const { location, cuisine, searchResults } = state;
//create cards with the results from the Yelp API GET
const YelpSearchResults = searchResults.map(result => (
<div className="ResultCard">
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src={result.image_url} />
<Card.Body>
<Card.Title>{result.name}</Card.Title>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroupItem>{result.categories}</ListGroupItem>
<ListGroupItem>{result.rating}</ListGroupItem>
</ListGroup>
<Button variant="primary">Book restaurant</Button>
</Card>
</div>
));
return (
<React.Fragment>
<div className="SearchMeal">
<Form onSubmit={handleSubmit}>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>City</Form.Label>
<Form.Control
name="location"
type="text"
value={location}
onChange={handleChange}
placeholder="location"
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Cuisine</Form.Label>
<Form.Control
name="cuisine"
type="text"
value={cuisine}
onChange={handleChange}
placeholder="cuisine"
/>
</Form.Group>
</Form.Row>
<Button type="submit">Submit</Button>
<Button>Clear</Button>
</Form>
</div>
{YelpSearchResults}
</React.Fragment>
);
};
export default SearchMealForm;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Categories

Resources