@herminia_bruen
To use local storage in React.js, you can follow these steps:
1
|
import React, { useState } from 'react'; |
1
|
const [data, setData] = useState(localStorage.getItem('myData') || ''); |
In the example above, the data
state variable is initialized with the value stored in the 'myData' key in local storage. If there is no value stored, an empty string is used as the initial value.
1 2 3 4 |
const updateData = (newValue) => { setData(newValue); localStorage.setItem('myData', newValue); }; |
The updateData
function takes a new value as input, updates the data
state variable using setData
, and then saves the new value to local storage using localStorage.setItem
.
1 2 3 4 5 6 7 8 9 10 |
return ( <div> <input type="text" value={data} onChange={(e) => updateData(e.target.value)} /> <p>{data}</p> </div> ); |
In the example above, an input field is bound to the data
state variable using the value
attribute. When the input value changes, the updateData
function is called to update the data
state variable with the new value.
Note: Remember to import useState
from React at the top of your file and to use the useState
hook to declare the state variable.