Discovering React.js: Key Basics for Newcomers
First two ways data binding
For example, if we type something in an input field directly, it updates the DOM. However, we don't need to do this because React uses a concept called the Virtual DOM. So, whenever we need to enter something in an input box, we shouldn't do it directly. Instead, we should inform React, and React will handle it for us using tools like useState
.
import React from 'react';
const App = () => {
return (
<div>
<h1>Input Form</h1>
<form>
<input
type="text"
placeholder="Enter something..."
/>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default App;
There is a concept of value
in an input field. If we set any default data in the value field, it appears in the input box, and we cannot edit or modify it directly in the input box.
<input
value="Hi"
type="text"
placeholder="Enter something..."
/>
To avoid this and use the Virtual DOM for input in React, we use the useState
hook and assign it to the value
. and initially, I keep inputValue
as an empty string.
But with this i also want to modify my code for, whenever i write something in input box it reflect to inputValue via useState. So iโm going to use onChange
import React from 'react';
const App = () => {
const [inputValue, setInputValue] = useState('');
return (
<div>
<h1>Input Form</h1>
<form>
<input
value={inputValue}
onChange={(e)=>{setInputValue(e.target.value)}}
type={inputValue}
placeholder="Enter something..."
/>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default App;
In both the first and last code snippets, I often think they are doing the same thing.
Yes, both pieces of code will do the same thing, but there is a small difference between them. In the first code, we need to use an alternative to useState
for rendering input data. However, in the second code, we don't write directly to the DOM, and it cannot modify the DOM. This code tells React to handle it for us. React uses setInputValue
to store the data from onChange
and updates the value accordingly.
This is what we call Two way Binding.
Happy Coding ๐
Subscribe to my newsletter
Read articles from RIMANSHU SINGH directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
RIMANSHU SINGH
RIMANSHU SINGH
I'm a passionate frontend developer with a knack for crafting immersive user experiences. Over the years, I've honed my skills in ReactJS, MongoDB, Redux, React-Toolkit, and SQL, leveraging these tools to deliver robust and dynamic web applications. I am passionate about explore and learning new things and willing to work beyond my capacity to administer projects. ๐ผ Currently, Diving deep into MEAN stack