'Input' is not defined react/jsx-no-undef, what does that mean? - reactjs

Im trying to make an input field for name in my code, and I get:
'Input' is not defined react/jsx-no-undef and I cant see whats wrong, can anyone please help me?
I will later pass name into my dispatch
The form part with textarea is working.
import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import '../styles/NewMessage.css'
import { fetchNewMessage } from 'reducer/messages'
export const NewMessage = () => {
const [message, setMessage] = useState('')
const [name, setName] = useState('')
const dispatch = useDispatch()
const handleMessageSubmit = (event) => {
event.preventDefault()
//console.log('addNewMessage', message)
dispatch(fetchNewMessage(message))
setMessage('')
}
return (
<div className="add-message-container">
{/* ******Form for sending a new message******* */}
<form onSubmit={handleMessageSubmit} className="add-message-form">
<span>
<label>
Name:
This input is giving me the 'Input' is not defined react/jsx-no-undef
<Input
placeholder="Name"
type="text"
onChange={event => setName(event.target.value)}
value={name}
required
/>
</label>
</span>
This textarea is working fine
<span>
<label For="new-message">
<textarea
id="new-message"
className="input-message"
rows='3'
minLength='5'
maxLength='150'
placeholder="Type your message"
onChange={(event) => setMessage(event.target.value)}
value={message}
required />
</label>
</span>
{/* * Form submit button * */}
<div className="add-message-btn-container">
<button
className="add-message-btn"
type="submit"
title="Send">
Send
</button>
</div>
</form>
</div>
)
}

You either need to import Input component from some component library or you need to use input which is the HTML element. JSX tags are case-sensitive, which is why it gives you are warning from eslint
<input
placeholder="Name"
type="text"
onChange={event => setName(event.target.value)}
value={name}
required
/>

it is <input> tag with small i.

Use <input /> instead of <Input />, as JSX attributes are case-sensitive

Related

Reactjs: How to clear text field after submission

I have a signup page which has 4 input text fields which changes the currentState of each field from an empty string to whatever I inputted. After signing up it logs each of the following 4 fields input in a database with a post request. How can I clear each field after clicking on the sign up button. Basically I just want the page to clear after clicking. I have attempted to set the state of the 4 variables back to an empty string at the end of my promise chain but nothing changes still.
import React,{useState} from 'react';
import style from './Signup.css';
import Axios from 'axios';
function Signup() {
const [firstReg, setFirstNameReg] = useState('')
const [lastReg, setLastNameReg] = useState('')
const [emailReg, setEmailReg] = useState('')
const [passReg, setPassReg] = useState('')
const register = () => {
Axios.post('http://localhost:3001/register', {
first_name: firstReg,
last_name: lastReg,
email: emailReg,
password: passReg,
}).then((response)=> {
console.log(response);
setFirstNameReg('')
});
};
return (
<div className="Signup">
<div className='Sign'>
<div class="photo"> Create an account</div>
<div class ='searche'>
<div className="searchInputse">
<input type="text" onChange={(e)=> {setFirstNameReg(e.target.value)}} placeholder={'First name'} />
<div className="searchIcone"></div>
</div>
<div className="dataResult"></div>
</div>
<div class ='searche'>
<div className="searchInputse">
<input type="text" onChange={(e)=> {setLastNameReg(e.target.value)}} placeholder={'Last name'}/>
<div className="searchIcone"></div>
</div>
<div className="dataResult"></div>
</div>
<div class ='searche'>
<div className="searchInputse">
<input type="text" onChange={(e)=> {setEmailReg(e.target.value)}} placeholder={'Email'}/>
<div className="searchIcone"></div>
</div>
<div className="dataResult"></div>
</div>
<div class ='searche'>
<div className="searchInputse">
<input type="text" onChange={(e)=> {setPassReg(e.target.value)}} placeholder={'Password'}/>
<div className="searchIcone"></div>
</div>
<div className="dataResult"></div>
</div>
<button className='searchee' onClick={register}>
Sign Up
</button>
</div>
</div>
);
}
export default Signup;
A few things you should be aware of.
1st. You want to keep your data in an object for easy management and code reduction like so:
Define the initial object outside of your component;
let initialValues = {
'first_name': '',
'last_name': '',
'email': '',
}
And inside your component define state with the initialValues variable as the state default.
const [data, setData] = useState(initialValues);
And then, in your JSX you can connect the values with the object keys like so:
<input type="text" name="first_name" value={data.first_name} />
<input type="text" name="last_name" value={data.last_name} />
<input type="text" name="email" value={data.email} />
You can also then add an onChange handler to that input like so:
note: name must match the key inside of the initalValues object.
<input type="text" name="first_name" value={data.first_name} onChange={handleChange} />
<input type="text" name="last_name" value={data.last_name} onChange={handleChange} />
<input type="text" name="email" value={data.email} onChange={handleChange} />
handleChange basic function can look like this:
const onChange = (e) => {
setData({...data, [e.target.name]: e.target.value})
}
Essentially all you're doing is typing inside the input field, onChange detects a change on each key press, and fires off the handleChange function, that function makes a copy of the current state of data then looks at the e.target.name which could be first_name and sets it to e.target.value which is anything you type.
That way, all you need to pass to axios is the data object.
I hope this helps, let me know if you have any other questions.
Happy coding!
Hi try to replace your register button with this :
<button className='searchee' onClick={()=>{register();setFirstNameReg('');setLastNameReg('');setEmailReg('');setPassReg('')}}>
Sign Up
</button>

Data Fetching with React using useEffect

What I am trying to do is when the user click the edit button, this will send him to a new page where he can modify the info he already entered. The problem I am facing is that the new page is not showing the data previously entered, so that the user can make his changes. Also, the submit button to send those changes is not working. These are the errors I am getting: src\components\RestaurantList.jsx
Line 25:8: React Hook useEffect has a missing dependency: 'setRestaurants'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Line 31:19: 'response' is assigned a value but never used no-unused-vars
src\components\UpdateRestaurant.jsx
Line 9:12: 'restaurants' is assigned a value but never used no-unused-vars
Line 38:8: React Hook useEffect has a missing dependency: 'code'. Either include it or remove the dependency array react-hooks/exhaustive-deps
My code for the component I am working on:
import React, {useState, useContext, useEffect} from 'react';
import { useHistory, useParams } from 'react-router-dom';
import RestaurantFinder from '../apis/RestaurantFinder';
import { RestaurantsContext } from '../context/RestaurantsContext';
const UpdateRestaurant = (props) => {
const {code} = useParams();
const {restaurants} = useContext(RestaurantsContext);
let history = useHistory();
const [name, setName] = useState("");
const [value, setValue] = useState ("");
const [strain, setStrain] = useState ("");
const [weight, setWeight] = useState ("");
const [authors, setAuthors] = useState ("");
const [number, setNumber] = useState ("");
const [page, setPage] = useState ("");
const [date, setDate] = useState ("");
useEffect(() => {
const fetchData = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setName(response.data.data.restaurant.name);
setValue(response.data.data.restaurant.value);
setStrain(response.data.data.restaurant.strain);
setWeight(response.data.data.restaurant.weight);
setAuthors(response.data.data.restaurant.authors);
setNumber(response.data.data.restaurant.number);
setPage(response.data.data.restaurant.page);
setDate(response.data.data.restaurant.date);
};
fetchData();
}, []);
const handleSubmit = async(e) => {
e.preventDefault();
const updatedRestaurant = await RestaurantFinder.put(`/${code}`, {
name,
value,
strain,
weight,
authors,
number,
page,
date,
});
console.log(updatedRestaurant);
history.push("/");
};
return (
<div>
<form action="">
<div className="form-group">
<label htmlFor="name">Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} code="name" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Value">Value</label>
<input value={value} onChange={(e) => setValue(e.target.value)} code="value" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Strain">Strain</label>
<input value={strain} onChange={(e) => setStrain(e.target.value)} code="strain" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Weight">Weight</label>
<input value={weight} onChange={(e) => setWeight(e.target.value)} code="weight" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Author">Author</label>
<input value={authors} onChange={(e) => setAuthors(e.target.value)} code="authors" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Number">Number</label>
<input value={number} onChange={(e) => setNumber(e.target.value)} code="number" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="Page">Page</label>
<input value={page} onChange={(e) => setPage(e.target.value)} code="page" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="date">Date</label>
<input value={date} onChange={(e) => setDate(e.target.value)} code="date" className="form-control" type="number" />
</div>
<button onClick={handleSubmit} type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
export default UpdateRestaurant
for reusable code, it may be best to just do something like this.
This is probably not the answer, but I hope it helps you find out the answer.
const [data, setData ] = useState({restraunt.loaded:"false"});
useEffect(() => {
const fetch = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setData({...response.data.data, restraunt.loaded:"true"});
};
fetch();
},[Data.restraunt.loaded])
const {name, value , page, loaded } = Data.restaurant;
return (
<div><h1>{loaded}</h1>
</div>
)
If it shows loaded as false then you know it is because of the data not loading.

Clear value into input using useState or useRef (React)

I got hook:
const [myName, setMyName] = useState("");
const myNameRef = useRef();
Then I have form:
<form onSubmit={(e) => addVist(e, user.id)}>
<input type="text" name="myName" ref={myNameRef} onChange={e => setMyName(e.target.value)} />
<input type="submit" value="Run" />
</form>
And method:
const addVist = (e, userId) => {
e.preventDefault();
console.log(myName)
//some code....
//clear value form
setMyName("");
//setMyName('');
//setMyName(e.target.value = "");
//myNameRef.current.value("");
}
But the setMyName("") is not working - still I see value inside input.
You missed binding myName as value attribute of the input tag.
<input type="text" name="myName" value={myName} ref={myNameRef} onChange={e => setMyName(e.target.value)} />
Here is a complete example of clearing input using state OR a reference:
export default function App() {
const [value, setValue] = useState("");
const inputRef = useRef();
return (
<>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<input ref={inputRef} />
<button
onClick={() => {
setValue("");
inputRef.current.value = "";
}}
>
Clear
</button>
</>
);
}
Refer to Controlled VS Uncontrolled components.
On your text input you should pass myName into the value attribute like so
<input type="text" name="myName" value={myName} ref={myNameRef} onChange={e => setMyName(e.target.value)} />
You forgot to add myName as value.
<input type="text" name="myName" value={myName} ref={myNameRef} onChange={e => setMyName(e.target.value)} />

Why is my handleChange method being rejected by React?

I am trying to do a simple form task to try and learn React Forms but I am having a hard time understanding the syntax of it.
When I try the following code it works no problem:
import React, { useState } from "react";
function InputForm() {
const [emailValue, setEmailValue] = useState("");
console.log(emailValue);
return (
<>
<form>
<label>
Email:
<input
type="text"
name="input"
value={emailValue}
placeholder="type your email"
onChange={(e) => setEmailValue(e.target.value)}
/>
</label>
<br />
<br />
<button type="submit" name="test">
Submit Email
</button>
</form>
</>
);
}
export default InputForm;
However, when I try to clean it up so that there is not logic within the return, I get an error when I define my handleChange method.
import React, { useState } from "react";
function InputForm() {
const [emailValue, setEmailValue] = useState("");
handleChange(e) {
const { name, value } = e.target;
setEmailValue({ [name]: value });
};
console.log(emailValue);
return (
<>
<form>
<label>
Email:
<input
type="text"
name="input"
value={emailValue}
placeholder="type your email"
onChange={handleChange}
/>
</label>
<br />
<br />
<button type="submit" name="test">
Submit Email
</button>
</form>
</>
);
}
export default InputForm;
Can someone please explain why doing it this way doesn't work? The error I'm getting is that React is not expecting the { bracket after handleChange(e)... so the console error messages are useless in trying to figure out why it's not accepting it.
Thanks!
It's not React rejecting anything, it's just that, well, that's not correct JavaScript syntax.
You'll want
function InputForm() {
const [emailValue, setEmailValue] = useState("");
const handleChange = (e) {
const { name, value } = e.target;
setEmailValue({ [name]: value });
};
// ...
(and even so you're mixing and matching state types -- you have a state atom that's ostensibly a string (since you initialize it with a "") and then you assign an object into it... You may be looking for setEmailValue(value); there.)

How can I get radio button value and upload it into firebase?

In this code, I want to upload the radio button value and store it in firebase database.I want use the simplest way to solve that. I see other code will use constructor but I do not know whether I can use simpler way to solve it. how can I do that ?
import React, { useState } from "react";
import ReactPlayer from "react-player";
import Array from "../Array";
import firebase from "firebase";
export default () => {
const [selected, setSelected] = useState("");
return (
<div>
<div className="video">
<ReactPlayer url={Array[0]} playing />
</div>
<label>Guess whether this video is fake or real ?</label> <br />
<label>
<input
type="radio"
name="answer"
value="real"
onChange={e => setSelected(e.target.value)}
/>
real
</label>
<label>
<input
type="radio"
name="answer"
value="fake"
onChange={e => setSelected(e.target.value)}
/>
fake
</label>
</div>
);
};
I would do it like this:
import React from "react";
....
export default () => {
const [state, setState] = React.useState({});
const handleInputChange = e => {
const { name, value } = e.target;
console.log(name, value);
setState(state => {
const newState = { ...state, [name]: value }
//post newState to firebase
return newState
});
};
return (
<div>
<div className="video">
<ReactPlayer url={Array[0]} playing />
</div>
<div>{JSON.stringify(state)}</div>
<label>Guess whether this video is fake or real ?</label> <br />
<label>
<input
type="radio"
name="answer1"
value="real"
onChange={handleInputChange}
/>
real
</label>
<label>
<input
type="radio"
name="answer2"
value="fake"
onChange={handleInputChange}
/>
fake
</label>
</div>
);
};

Resources