DEV Community

Avinash Kr
Avinash Kr

Posted on

Change behaviour of button on different pages.

I am creating a React app like blogging page. In the navbar I have included three buttons:
1.Write
2.Your Articles - to view articles posted by the user
3:Logout

image

Now I wanted to change behavior of Write button to submit type when I am writing articles and change text to Publish.
Here is expected output:

image

I did google and read some articles but was not getting proper solution.

To solve this problem:

  1. I passed submitHandler method as prop from parent component to Navbar
  2. created a newstate using useState hook in parent component and passed as prop. I defined newstate like this:

const [navitems, setNavitems] = useState({
item1:{text:"Write",type:'submit'}, item2:{text:'Your Article',type:''}, item3:{text:'Logout',type:''}
});

passed newstate as prop to navbar.
In total there are two props passed to navbar.(submitHandler, navitems)

setter method is passed as prop to component, which will render when we are writing article, call it as "createComponent"

In the createComponent I called setter method "setNavitems" in useEffect and changed the button text=Publish and type=submit;

Since I have written article in createComponent I have to submit it from the same page to send data to server but as per the design wireframe I have to remove submit button and and submit through publish button which is in another component(Navbar).

To solve this I thought to render a different navbar looking very similar to previous and hide original. I did not liked the solution as it was using more resources for small functionality, I was rendering a complete new DOM node.

Then I used another way, passed the same submitHandler as prop to createComponent and called it onSubmit event, parent of Navbar and createComponet are same so I lifted the state and passed a new state as props to the createComponent
here it is:
image

article is not handlingchange on createComponent and it is is stored in parent component.

Finally I was able to submit the article from the parent component by calling calling dispatch in submitHandler function

Top comments (0)