Skip to content
Advertisement

How to update texts in React

Good evening everyone, I am trying to create an online application to take quizzes in order to practice for exams. My problem is as follows:

I have the following ‘App’ component:

JavaScript

And its output is the following image: enter image description here

Where as we can see, the active navbar element and the Home sign that is between the navbar and the component below corresponds with the path “localhost:3000/home”.

When I choose another navbar element such as Statistiche, the path changes correctly, but the element in the navbar doesn’t change the state or even the Home text. This only happens if I refresh the page. notUpdatedContent

Reading on the net, I see that useState() is used, I just don’t have any vague idea how to go about implementing this stuff! Please help me out! Thank you in advance for the trivial question, it would change my life if you could explain me how the mechanism works!

Advertisement

Answer

I solved the problem in the following way:

I’ve created a state variable:

JavaScript

That as soon as the page is loaded it deduces from the path the name of this.

Then inside the <Link > tag i’ve added, in the attribute onClick, the following lambda function onClick={() => setPageName(item.nome)}. So every time I click on another link the name is updated immediately (it changes his state).

Finally the file become:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement