DEV Community

ivadam00
ivadam00

Posted on

I have a question .

how do i change or remove state value when i click to a link or navigation link and it should render that link page in react.
if anyone know please tell me..

edit :-

so here is my problem which im asking for help

assume i have basic react app code here like some routes..

//app.jsx
import from "./components/MainHomePage"
import from "./components/About"
import from "./components/Contact"

import {
  createBrowserRouter,
  createRoutesFromElements,
  Route,
  RouterProvider,
} from "react-router-dom";

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<RootLayout />}>
      <Route index element={<Navbar />} />
      <Route index element={<MainHomePage />} />
      <Route path="about" element={<About />} />
      <Route path="contact" element={<Contact />} />
      <Route path="blog" element={<Blog />} />
    </Route>
  )
);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

Enter fullscreen mode Exit fullscreen mode

assume i have some content written in each route page
now look into my navbar component

//Navbar.jsx
import {useState} from "react"

const Navbar = () => {

const [text, setText] = useState('')

const handleChange = (e) => {
       setText(e.target.value)
}

const handleSubmit = (e) => {
       e.preventDefault() //prevent default page refresh behavior
       setText('') //to empty input box
}
return (
    <nav>
       <ul className="navbar-links">
         <li> 
            <Link to={"/"}> Home </Link>
         </li>
         <li> 
            <Link to={"/contact"}> Contact </Link>
         </li>
         <li> 
            <Link to={"/about"}> About </Link>
         </li>
         <li> 
            <Link to={"/blog"}> Blog </Link>
         </li>
       </ul>

       <div className="navbar-search-box">
         <form onSubmit={handleSubmit}>
             <input type="text" value={text} onChange={handleChange}>
             <button type="submit"> Search </button> 
         </form>
       </div>
    </nav>
)
}
Enter fullscreen mode Exit fullscreen mode

here is my root layout component

//RootLayout.jsx

import Navbar from "./component/Navbar"
import {Outlet} from "react-router-dom"

const RootLayout = () => {
    return(
     <>
       <Navbar />
       <Outlet />
     </>
)
}
Enter fullscreen mode Exit fullscreen mode

so now i want to do when i type in the search input box and when i click on search button it will set state to that text and render result page or any particular result but when click to any other navlink from navbar my result page whatever we searched it is not changing the state to empty and my new page whichever we clicked from navbar is not rendering becuase of state, it is a bug so how do i solve this after searching and when i want to navigate to other navbar pages i want to remove result page and state should be empty and render new route page..

i hope i explained ...

Top comments (6)

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Please, add the tags #react #help and #javascript or #typescript (depending on what you are using) to this discussion and provide some source in which we can check the code to give proper directions.

On the other hand, please add detailed acceptance criteria on what do you want to achieve and also define, following the same rules what is currently happening.

This way we can help you better.

Thank you! 😁

Collapse
 
ivadam00 profile image
ivadam00

please check edited post

btw thank you for your suggestion, im newbie in the web dev community

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Solution

I can see that you remove the state explicitly inside the handleSubmit function

const handleSubmit = (e) => {
       e.preventDefault();
       setText(''); // <- HERE
}
Enter fullscreen mode Exit fullscreen mode

So instead of applying the search logic (which I fail to find in your code), you are resetting the value of the state to an empty string... πŸ˜…

*Check on that and come back either to confirm that the issue is gone or to add further details if the issue persists.*

Debugging

Also you will do good by installing the React Developer Tools Chrome Extension and checking a tutorial on how to use it and learn how to debug.

In VSCode you can add (if not yet present) a directory with the name .vscode to the root of your project and a launch.json file inside, which contents should look like that:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ReactJS: debug",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3000"
    },
  ]
}
Enter fullscreen mode Exit fullscreen mode

So you will be able to run the debugger (F5 shortcut), add break points and inspect the values of each thingy in a given point of time during the runtime execution of your software, hence spotting real quick which is the issue.

Suggestions / side-notes

You said you're a newbie on web development. I don't know if you are following a learning path or not, but if you don't I'd suggest you to do so. There are multiple paths you can find out there, maybe one of the best if you want free resources is FreeCodeCamp, and the order for frontend is as follows:

1- Responsive Web Design.
2- JavaScript Algorithms and Data Structures.
3- Front End Development Libraries (<-- this is React).
4- Data Visualization (<-- this is D3, which you can combine with React later on).
5- Quality Assurance (or fall back to any course on Jest + React-testing-library).

Best regards

Thread Thread
 
ivadam00 profile image
ivadam00

oh sorry it was my mistake i forgot to write search logic, so the logic was the data is coming from the api

//search logic
const [text, setText] = useState('')
const [searchTerm, setSearchTerm] = useState(" ") //empty string
const [searchResult, setSearchResult] = useState([]) //empty array

const handleChange = (e) => {
       setText(e.target.value)
}

const handleSubmit = (e) => {
       e.preventDefault() //prevent default page refresh behavior
      if(text){
       setSearchTerm(text)
       setText('') //to empty input box
     }

}

const searchHandle = async (searchTerm) => {
      const {data} = await axios.get(`www.example-api.com/details/s?val=${searchTerm}`}
     if(data){
          setSearchResult(data)
        }
}
Enter fullscreen mode Exit fullscreen mode

i want to show search result in the result component and when i clicked to submit it gets me the result but when i click to another link page state is still there

and thank you for the roadmap...i will surely follow this.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Hi, it is somewhat difficult to follow having pieces of code isolated.

Please follow the Debugging section above so you can check which values you have in the variables at each point of the runtime. You will probably be able to troubleshoot it yourself 😁

Collapse
 
ivadam00 profile image
ivadam00

thank you for the comment
please check edited post i explained..
help me thank you again :)