I have a simple component below named Idea:
import './Idea.css';
import { useState } from 'react';
import { useParams } from 'react-router-dom';
function Idea() {
const { id } = useParams();
const [ test, setTest ] = useState('');
console.log('Idea rendered');
const handleChange = (event) => {
setTest(event.target.value);
};
return (
<form>
<input onChange={handleChange} value={test}/>
</form>
);
};
export default Idea;
Each instance of this component is rendered using react-router via dynamic routing, as shown in the second route component below:
function App() {
return (
<Provider store={store}>
<BrowserRouter>
<main>
<SideBar />
<section id='main-window'>
<Routes>
<Route exact path="/" element={ <Instructions /> } />
<Route path="/ideas/:id" element={ <Idea/> } />
</Routes>
</section>
</main>
</BrowserRouter>
</Provider>
);
};
The problem is illustrated in this example: Let's say I am on route /ideas/1234 and its input value says hello world!. If I switch to route /ideas/5678 then the input on that route will also say hello world! even though I specified the input value to say otherwise upon render. If I change the input value on route /ideas/5678 the input value on route /input/1234 will change as well. They will inevitably both be the same value as if they're the same, regardless of the route. This started happening when I introduced the useState hook in the Idea component. I assume useState should reset the input value every time I change a route but this does not seem to happen.