How can I make use of React.js refs without a variable? - javascript

Given the source code for a simple login form, see below. You see I want to use the username text field's value when I click the form's submit button. Since I need a reference to the actual DOM node to retrieve the value, I'm setting the usernameElement variable to that node.
const Login = ({ onLogin }) => {
let usernameElement
const handleSubmit = event => {
event.preventDefault()
onLogin(usernameElement.value)
}
return <form onSubmit={handleSubmit}>
<input
type="text"
name="username"
ref={node => { usernameElement = node }}
/>
<button type="submit">Login</button>
</form>
}
So, how would I make an functional approach to that problem, or simply get rid of the let variable?

Apparently, the correct approach to this is to make use of the component's state, meaning you need a stateful component instead of the stateless one.
// untested
class Login extends Component {
state = { username: '' }
handleChange = event => {
this.setState({ username: event.target.value })
}
handleSubmit = event => {
event.preventDefault()
this.props.onLogin(this.state.username)
}
render = () =>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="username"
value={this.state.username}
onChange={this.handleChange}
/>
<button type="submit">Login</button>
</form>
}
Using this, the username is always bound to this.state.username. The handleSubmit method can just use the username from the component's state.
See this page for further information: https://facebook.github.io/react/docs/forms.html

Related

How to get React state array to permanently update

I'm learning Node and React and now know how to integrate them and am working on making registration and login using Node and React. I'm going step by step, so currently I'm trying to at least get the inputs and put them into state as an array, and then after I get that I will go to hashing the password, sending the data to Node and the database, et cetera.
At the moment however, I'm a little bit stuck here. I'm trying to enter the username and password into my "details" state and then render it on the screen (or console log it, or whatever), but when I do it it shows up very quickly and then disappears. Why is the details state reverting to an empty array? How do I fix it? I did some research on here but couldn't figure it out.
import { useState } from 'react';
function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [details, setDetails] = useState([]);
const readUsername = (e) => {
setUsername(e.target.value);
}
const readPassword = (e) => {
setPassword(e.target.value);
}
const updateDetails = () => {
setDetails([username, password]);
}
return (
<div>
<h1>Register</h1>
<form>
<label htmlFor="username" name="username">Username: </label>
<input htmlFor="username" name="username" onChange={readUsername} />
<br/>
<label htmlFor="password" name="password">Password: </label>
<input htmlFor="password" name="password" type="password" onChange={readPassword} />
<br/>
<button onClick={updateDetails}>Submit</button>
</form>
<h1>{details}</h1>
</div>
);
}
export default App;
with the onChange handler on your input's, it is considered a "controlled" component. you also need to assign the value prop.
<input onChange={readUsername} value={username} />
Forms in React have the default behaviour as in HTML: refreshing the page upon submission.
React state only exists during the component's life. When you refresh the page, the component is unmounted, and the state is lost.
To prevent the page refresh, use a function to handle the form submission, and prevent the default behaviour.
const handleSubmit = (e) => {
e.preventDefault();
}
return (
...
<form onSubmit={handleSubmit}>
...
</form>
...
);
}
View demo on codesandbox
Further reading:
Forms in React
Preventing default behaviour of events
You want to create a controlled input so you should pass the value={password} attribute
like this:
<input htmlFor="username" name="username" onChange={readUsername} value={username} />
Also, I'd change how you handle to form. Change the button to type="submit"
like this
<button type="submit">Submit</button>
And then handle the submit from the <form>
like this:
<form onSubmit={(event) => updateDetails(event)}
And then on the function, you can use the submit event like this for example
const updateDetails = (e) => {
event.preventDefault()
...rest of logic
}

How to update input value react

I have a list and edit button when user click edit button opening a new modal. I want to auto populate the selected username mail etc. Server side response is {this.test.name} i give him to input value to auto populate but when user click edit button ı can see the name but ı couldnt change the input how do ı do that ?
Code :
<div className = "form__group field">
<input type="input" className="form__field" placeholder="Name" name="name" id="name" value={this.test.name} />
<label htmlFor="name" className="form__label">Adı-Soyadı</label>
</div>
You cannot change that input value because you've set the value to this.test.name and did not defined an onChange handler. So what you should do is create a state for your input field and on componentDidMount, populate this state with data from server.
Then on your input field
this.state = {
val: ''
}
<input value={this.test.name} onChange={e => setState({val: e.target.value})}/>
Maybe there can be a syntax error, because I am used to work with hooks now, but that's pretty much the gist of it
Keep the name in the state:
this.state = {
name: '',
}
(setState when you have it, if you retrieve it only on mount)
Pass value={this.state.name} to the input.
Pass onChange={handleNameChange} to the input.
const handeNameChange = (e) => {
setState({ name: e.target.value });
}
If you are using hooks, you could do something like this:
import { useState } from "react"; // import useState
export default function App() {
const [name, setName] = useState(""); // useState hook
// handle change event
const handleChange = (e) => {
e.preventDefault(); // prevent the default action
setName(e.target.value); // set name to e.target.value (event)
};
// render
return (
<div>
<input value={name} type="text" onChange={handleChange}></input>
<p>{name}</p>
</div>
);
}
First, we import the useState() hook to be able to use it, then we use it to store the state for the name value, you can give it an initial value of an empty string (""). In the handleChange() function, we prevent the default action and set the state to e.target.value, this is the input value passed by the event (as (e)). Every time the input changes, the state will update and the page will re-render.
You could check out my sandbox here

State not being updated in React.js

I have created a basic form in react.js where I am able to get the values after the user submits the form.
However, when I try to change the values using the handleSubmit function, I don't see the changes made in the state.
I have made a copy of a state and changes are being reflected in the Copied State. But when I set the old state equal to the updated state, the changes are not reflected
My code is as follows
state = {
name: null,
ContactNumber: null
}
handleChange = (event) => {
this.setState({
[event.target.name] : event.target.value
})
}
handleSubmit = (event) => {
event.preventDefault()
let Copystate = JSON.parse(JSON.stringify(this.state))
Copystate.ContactNumber = 100
console.log(Copystate) // displaying the contact number as 100
this.setState({
state : Copystate
})
console.log(this.state) // displays the number which was submitted in the form
}
render(){
return(
<div>
<h2>Form</h2>
<form onSubmit={this.handleSubmit}>
<div>
<label>Name</label>
<input type="text" name="name" required = {true} onChange = {this.handleChange}/>
<label>Contact Number</label>
<input type="number" name="ContactNumber" required = {true} onChange = {this.handleChange}/>
<button type="submit" label="submit" >Submit</button>
</div>
</form>
</div>
);
}
}
Can anyone please let me know where I am going wrong? Thanks
Notice: setState is asynchronous: document state-updates-may-be-asynchronous
You can use a callback function to get the updated state
this.setState({state: Copystate}, () => {console.log(this.state)});
Or you can choose to use async/await
handleSubmit = async (event) => {
await this.setState({state: Copystate});
console.log(this.state);
}
Those two methods won't affect re-render since once the state is been updated, the re-render would proceed.
If you console in the render() you would find that it should always be updated finally.
render() {
console.log(this.state);
return (
...
)
}
setState is asynchronous.
So, you can do one of the following -
1. make a callback in setState to log the state or
2. write your console statement in the render function.
Why do you do this?
let Copystate = JSON.parse(JSON.stringify(this.state))
Copystate.ContactNumber = 100
You can change the handleSubmit to be like the following:
handleSubmit = (event) => {
event.preventDefault();
let { ContactNumber } = this.state;
ContactNumber = 100;
console.log(ContactNumber); // displaying the contact number as 100
this.setState({
ContactNumber: ContactNumber
}, () => {
console.log(this.state) // displays the number which was submitted in the form
})
}

I'm having trouble changing the value in input

Part of the project is as follows:
...
const INITIAL_STATE = {
email: '',
password: '',
error: null
}
const SignInPage = () => {
return(
<div>
<h2>Sign In</h2>
<SignInForm/>
<SignUpLink/>
</div>
)
}
const SignInFormBase = props => {
const[init,setInit] = useState(INITIAL_STATE);
const onSubmit = () => {
}
const onChange = (event) => {
setInit({
[event.target.name]: event.target.value
})
}
const isInvalid = init.password === '' || init.email === '';
return(
<form onSubmit={onSubmit}>
<input
name='email'
value={init.email}
onChange={onChange}
type='text'
placeholder='Email Address'
/>
<input
...
/>
<button disabled={isInvalid} type='submit'>Sign In</button>
{init.error && <p>{init.error.message}</p>}
</form>
)
}
const SignInForm = compose(
withRouter,
withFirebase
)(SignInFormBase)
export default SignInPage;
export {SignInForm}
The problem is:
When I replace the values ​​in init with setInit in the onChange function, I get the following error.
Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa) . Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Note: I have the same problem in the password section
You strip part of the code but I assume that you didn't read react hooks documentation good enough. By using hooks you won't get replacement for the setState which was previously merging the values. Therefore when you call
setInit({
[event.target.name]: event.target.value
})
you will replace whole init variable with the new object therefore other field will be pointing to undefined value and react will change component to uncontrolled, then again to controlled when you enter value. If you want to maintain object in state you need to do merging by yourself. Easiest way would be to use object spread as
setInit({
...init, // <- spread old state
[event.target.name]: event.target.value
})
With this code old state will remain between inputs. I would also suggest you to not infer state property from the field name as later you can easily introduce bug you can create curried global onChange as
const onChange = (field) => (event) => {
setInit({
...init,
[field]: event.target.value
})
}
return (
<input onChange={onChange('name')} />
)

ReactJS : Form Data Capture : values not setting properly

I am trying out with a small react app, with a form based data capture, after keying in the values, when user clicks submit button, values need to be captured in state variable. But, state variable contains null value in handleSubmit function. For clarity, code snippets are given below,
Constructor code, for the sake of completeness/clarity,
constructor(props)
{
super(props);
this.state = {
username : '',
};
}
handleChange function is where I set state variable,
handleChange = (event) => {
this.setState( [event.target.username]: event.target.value );
}
handleSubmit function is where, I print state variable, which contains null value, instead of user inputted value.
handleSubmit = () => {
console.log(this.state.username);
}
Component's render function is given below, which invokes handleChange
and handleSubmit.
render() {
return(
<div>
<form>
<label>
Title:
<input
type = "text"
name="username"
onChange={event => this.handleChange(event)}/>
</label>
<button
label="Submit"
onClick={this.handleSubmit}>
Submit
</button>
</form>
</div>
)};
I am missing on something. I am new to react. Kindly advise.
you need setState's argument to be an object.
handleChange = (event) => {
this.setState({ [event.target.username]: event.target.value });
}

Categories