Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a controlled React component for the input field (security wise)?

I made a React controlled component for the password input field:

onPasswordChange(ev) {
  this.setState({
    passoword: ev.target.value
  });
}

<input
  value={this.state.password}
  onChange={this.onPasswordChange}
>

As you can see in the image below if the component is controlled we can see the password value if I go and inspect the element. My question is: Is this the right way to control a password input? (security wise).

enter image description here

I know that I can use the ref={} on the input field but I want to know the best practices on handling password fields.

like image 256
Ioan Ungurean Avatar asked Aug 10 '17 08:08

Ioan Ungurean


People also ask

Why do we need controlled components in React?

In React, Controlled Components are those in which form's data is handled by the component's state. It takes its current value through props and makes changes through callbacks like onClick,onChange, etc. A parent component manages its own state and passes the new values as props to the controlled component.

What do controlled components do in React?

What are controlled components in React? Controlled components in React are those in which form data is handled by the component's state. Forms are used to store information in a document section. The information from this form is typically sent to a server to perform an action.

What's the difference between a controlled component and an uncontrolled one in React?

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself. To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

What are controlled inputs in React?

controlled input is an input that gets its value from a single source of truth. For example the App component below has a single <input> field which is controlled: class App extends React. Component { constructor(props) { super(props); this.


1 Answers

That's an interesting question but I don't think it's really a problem. From my knowledge, I think that you could always access the value of the input field if you have access to the inspector by using document.getElementById('passwordInputId').value for example. The password type is set so that someone behind you can't see what you are writing. This is a good example of what I'm talking about.

So you should probably use the controlled component with the state, since it's the way recommended by React and it's better to avoid refs.

like image 103
César Landesa Avatar answered Oct 17 '22 01:10

César Landesa