hide input field using hook in react - javascript

I have 4 input fields.
username,password,email,mobile.
if we type # in username field, the email field should disappear and if we type any digit in username then mobile field should disappear.
Help me with this.
I have created very basic code but not sure how to achive this.
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState();
if (name.includes("#")) {
setShow( ) //stuck here
}
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<input type="email" placeholder="email" id="email" />
<input type="number" placeholder="number" />
</>
);
}

Try below code
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
//****************************************
const [show, setShow] = useState(false);
//****************************************
if (name.includes("#")) {
//****************************************
setShow(true) //stuck here
//****************************************
}
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
//****************************************
{ show?
<input type="email" placeholder="email" id="email" />:''}
//****************************************
<input type="number" placeholder="number" />
</>
);
}

we can use with && operator if our show is false then it hide on screen
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState(true);
if (name.includes("#")) {
setShow(false) //stuck here
}
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{show && <input type="email" placeholder="email" id="email" />}
<input type="number" placeholder="number" />
</>
);
}

I'll give example with the email - you can apply same approach for the phone.
Some notes: you do not need a separate state whether to show email filed, it is derived from the name state.
Advice: You should not change state during the function render. You can do that on a user interaction (onClick, onChange etc) or useEffect hook if data fetch or another side effect.
The solution is simple
import { useState } from "react";
export default function App() {
const [name, setname] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState();
const showEmailField = name.includes("#"); //derived computed value base on the name state
return (
<>
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{ showEmailField && <input type="email" placeholder="email" id="email" /> }
<input type="number" placeholder="number" />
</>
);
}

you can try using the useEffect hook.
try something like this .
in this way you can keep track of everytime name changes
useEffect(() => {
if (name.includes("#")) {
setShow();
}
}, [name]);
and then
show && (
<input
type="text"
placeholder="username"
value={name}
onChange={(e) => setname(e.target.value)}
/>
)

Related

Reset button does not clear inputs in React

I have this simple form in my App form. I learned that a button with type="reset" clears the inputs, but it isn't working here with React. Am I missing something?
import { useState } from "react";
export default function App() {
const [name, setName] = useState("");
return (
<form>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
name="name"
/>
<button>Submit</button>
<button type="reset">Reset</button>
</form>
);
}
You must reset the state name with an empty string when the reset button is clicked.
export default function App() {
const [name, setName] = useState("");
const onClickReset = () => setName('');
return (
<form>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
name="name"
/>
<button>Submit</button>
<button type="reset" onClick={onClickReset}>Reset</button>
</form>
);
}
import { useState } from "react";
export default function App() {
const [name, setName] = useState("");
return (
<form>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
name="name"
/>
<button>Submit</button>
<button type="reset" onClick={() => setName('')}>Reset</button>
</form>
);
}
Use an object to maintain the initial state of the form and on RESET, update the state using the initial object.
Also, use event.preventDefault() to prevent the default action of the reset button.
const {useState} = React;
function App() {
const initState = {
name:''
};
const [name, setName] = useState(initState.name);
const onReset = (e)=>{
e.preventDefault();
setName(initState.name);
}
return (
<form>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
name="name"
/>
<button>Submit</button>
<button type="reset" onClick={e=>onReset(e)}>Reset</button>
</form>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
)
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
The reason for this is that your input is now controlled by a state, if you want to clear the form by type='reset' try removing the value and onChange attributes in your input. but if you want to clear the state you can create a function that will handle this. here's a sample function for your reference.
function handleClear() {
setName('')
}
<button type="button" onClick={handleClear}>Reset</button>

i am trying to add user information to firebase createuserwithemailandpassword

Whenever I try to add the user data, the wrong uid is being applied to the user data, it is applying the uid from the previous account created even after i have deleted the account from the database.
I read that i must create a child node to add the remaining user credentials which is what I am trying to do. But the current uid from the recieved promise is not being sent to the user database. please help.
second image
import React, { useState } from 'react'
import {v4 as uuid} from 'uuid'
import {db} from '../Features/util/firebase'
import {set,ref} from 'firebase/database'
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
function Register() {
const [fname, setFname]=useState('');
const [lname, setLname]=useState('');
const [phone, setPhone]=useState('');
const [email, setEmail]=useState('');
const [address, setAddress]=useState('');
const [username, setUsername]=useState('');
const [password, setPassword]=useState('');
const [uid, setUid]= useState('');
const createUser=(e)=>{
e.preventDefault();
const auth = getAuth();
createUserWithEmailAndPassword(auth,email,password)
.then((userCredential)=>{
console.log("signed in")
const user = userCredential.user;
console.log(user.uid);
setUid(userCredential.user.uid)
})
.then(()=>
set(ref(db,'users/') , {
fname:fname,
lname:lname,
phone:phone,
email:email,
address:address,
username:username,
userId:uid,
}))
.catch((error)=>{
const errorCode = error.code;
const errorMessage = error.message;
clearFields();
});
function clearFields (){
setAddress('');
setEmail('');
setFname('');
setLname('');
setPassword('');
setPhone('');
setUid('');
setUsername('');
}
}
return (
<div>
<form onSubmit={createUser}>
<label >First Name: </label>
<input type='text' value={fname} onChange={(e) => setFname(e.target.value)} required/><br/>
<label >Last Name: </label>
<input type='text' value={lname} onChange={(e) => setLname(e.target.value)} required ></input><br></br>
<label > Phone No.: </label>
<input type='tel' value={phone} onChange={(e) => setPhone(e.target.value)} required></input><br></br>
<label >e-Mail: </label>
<input type='email' value={email} onChange={(e) => setEmail(e.target.value)} required></input><br></br>
<label >Address: </label>
<input type='text' value={address} onChange={(e) => setAddress(e.target.value)} required></input><br></br>
<label >Username: </label>
<input type='text' value={username} onChange={(e) => setUsername(e.target.value)} required></input><br/>
<label >Password: </label>
<input type='password' value={password} onChange={(e) => setPassword(e.target.value)} required></input>
<input type='submit'></input>
</form>
</div>
)
}
export default Register
I was able to solve the problem with a different approach:
userId:auth.currentUser.uid,

How do I make a POST request using axios in react?

I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated!
Full Code:
import axios from 'axios';
import React, { useState } from 'react';
import { Container, Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
const AddContact = () => {
const [first_name, setFirstName] = useState("")
const [last_name, setLastName] = useState("")
const [mobile_number, setMobileNumber] = useState("")
const [home_number, setHomeNumber] = useState("")
const [work_number, setWorkNumber] = useState("")
const [email_address, setEmailAddress] = useState("")
const history = useNavigate();
const AddContactInfo = async () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
await axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
return (
<div>
<h1>Add contact</h1>
<Container>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your First Name"
first_name="first_name"
value={first_name}
onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Last Name"
last_name="last_name"
value={last_name}
onChange={(e) => setLastName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Mobile Number"
mobile_number="mobile_number"
value={mobile_number}
onChange={(e) => setMobileNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Home Number"
home_number="home_number"
value={home_number}
onChange={(e) => setHomeNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Work Number"
work_number="work_number"
value={work_number}
onChange={(e) => setWorkNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Email Address"
email_address="email_address"
value={email_address}
onChange={(e) => setEmailAddress(e.target.value)} /></div>
<Button onClick={() => { AddContactInfo(); }}>
Add Contact
</Button>
</Container>
</div >
);
};
export default AddContact;
First rename AddContactInfo to addContactInfo and then:
<Button onClick={addContactInfo}>
Add Contact
</Button>
You should correct the method addContactInfo as below:
const AddContactInfo = () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
Try This:
<Button onClick={AddContactInfo}>
Add Contact
</Button>
import axios from 'axios';
const url = 'http://localhost:8000/api/';
axios.post(url , formField)
.then(response => {
console.log(response.data);
history('/', { replace: true });
})
.catch(({response}) => {
console.log(response);
});
Try calling the function this way :)
<Button onClick={AddContactInfo}>
Add Contact
</Button>

form submission doesn't work when press 'enter' key

When I press enter key I get this error: Form submission canceled because form is not connected. But Add User button work right.
function Form({ modal, showModal, onAddUser }) {
const [name, setName] = useState('');
const [surname, setSurname] = useState('');
const [age, setAge] = useState('');
const createUser = (e) => {
if (!name || !age || !surname) {
return;
} else {
onAddUser(name, age, surname)
console.log(name, age)
}
setName('');
setAge('')
setSurname('');
showModal(false)
console.log(e);
}
return (
<>
{modal ? <FormContainer onSubmit={createUser}>
<InputContainer value={name} onChange={(e) => setName(e.target.value)} type="text" placeholder="Enter name" />
<InputContainer value={age} onChange={(e) => setAge(e.target.value)} type="number" placeholder="Enter age" />
<InputContainer value={surname} onChange={(e) => setSurname(e.target.value)} type="text" placeholder="Enter surname" />
<Button style={{ marginRight: "10px" }} type="cancel" onClick={() => showModal(false)}>Cancel</Button>
<Button type="button">Add User</Button>
</FormContainer>
: (null)
}
</ >
)
}
You should change the "Add User" button type to submit instead of button.
Also, you should call e.preventDefault() on the form submission.
Your component should be like this,
function Form({ modal, showModal, onAddUser }) {
const [name, setName] = useState('');
const [surname, setSurname] = useState('');
const [age, setAge] = useState('');
const createUser = (e) => {
// add this line here to prevent `form` element default behaviour
e.preventDefault();
if (!name || !age || !surname) {
return;
} else {
onAddUser(name, age, surname)
console.log(name, age)
}
setName('');
setAge('')
setSurname('');
showModal(false)
console.log(e);
}
return (
<>
{modal ? <FormContainer onSubmit={createUser}>
<InputContainer value={name} onChange={(e) => setName(e.target.value)} type="text" placeholder="Enter name" />
<InputContainer value={age} onChange={(e) => setAge(e.target.value)} type="number" placeholder="Enter age" />
<InputContainer value={surname} onChange={(e) => setSurname(e.target.value)} type="text" placeholder="Enter surname" />
<Button style={{ marginRight: "10px" }} type="cancel" onClick={() => showModal(false)}>Cancel</Button>
{/* here we changed type="button" to type="submit" */}
<Button type="submit">Add User</Button>
</FormContainer>
: (null)
}
</ >
)
}

Not hitting `debugger` statement in `handleOnSubmit`

I'm having a pretty specific problem in my React with Rails API backend app. I have a Redux form that I am using to create a new object, a real estate listing. The state is changing in my onChange function but when I click submit, the page refreshes and nothing was created. I put debugger inside my handleOnSubmit and it’s not hitting, any ideas?
ListingForm.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { updateListingFormData } from '../actions/listingForm';
import { createListing } from '../actions/listings';
class ListingForm extends Component {
handleOnChange = event => {
const { name, value } = event.target;
const currentListingFormData = Object.assign({}, this.props.listingFormData, {
[name]: value
})
this.props.updateListingFormData(currentListingFormData)
}
handleOnSubmit = (event) => {
debugger;
event.preventDefault()
this.props.createListing(this.props.listingFormData)
}
render() {
const { title, price, location, description, img_url, agent_name, agent_number, agent_email } = this.props.listingFormData;
return (
<div className="ListingForm">
<h3>Add New Listing</h3>
<form onSubmit={(event) => this.handeOnSubmit(event)}>
<label htmlFor="listing_title">Title</label>
<input
type="text"
name="title"
value={title}
onChange={(event) => this.handleOnChange(event)}
placeholder="Listing Title"
/>
<label htmlFor="listing_location">Location</label>
<input
type="text"
name="location"
value={location}
onChange={(event) => this.handleOnChange(event)}
placeholder="Listing City or County"
/>
<label htmlFor="listing_price">Price</label>
<input
type="integer"
name="price"
value={price}
onChange={(event) => this.handleOnChange(event)}
placeholder="Listing Price"
/>
<label htmlFor="listing_description">Description</label>
<input
type="text"
name="description"
value={description}
onChange={(event) => this.handleOnChange(event)}
placeholder="Listing Description"
/>
<label htmlFor="listing_image">Attach Image</label>
<input
type="text"
name="img_url"
value={img_url}
onChange={(event) => this.handleOnChange(event)}
placeholder="Listing Image"
/>
<label htmlFor="agent_name">Listing Agent</label>
<input
type="text"
name="agent_name"
value={agent_name}
onChange={(event) => this.handleOnChange(event)}
placeholder="Agent Name"
/>
<label htmlFor="agent_number">Listing Agent Phone</label>
<input
type="text"
name="agent_number"
value={agent_number}
onChange={(event) => this.handleOnChange(event)}
placeholder="Agent Phone"
/>
<label htmlFor="agent_email">Agent Email</label>
<input
type="text"
name="agent_email"
value={agent_email}
onChange={(event) => this.handleOnChange(event)}
placeholder="Agent Email"
/>
<button type="submit"> Add Listing</button>
</form>
</div>
)
}
}
const mapStateToProps = state => {
return {
listingFormData: state.listingFormData
}
}
export default connect(mapStateToProps, {updateListingFormData,createListing})(ListingForm);
In your form onSubmit you've misspelt handleOnSubmit (you left out the l)

Categories