简体   繁体   中英

how to auto refresh (NOT RELOAD) a component (after submitting a form) in ReactJS

After submitting the form using Add Button, I want the contents added to be displayed directly without refreshing the page url (NOT LOOKING FOR WINDOW.LOCATION.RELOAD). How do i make it work using ReactJS?

Add a custom event handler for the submit -event.

 function handleSubmit(event) { event.preventDefault() const text = new FormData(event.target).get("my_text") console.log("text:", text) // handle event manually // axios.post(event) document.querySelector("span").innerText = text }
 <form onsubmit="handleSubmit(event)"> <input type="text" placeholder="my_text" name="my_text"> <button type="submit">Submit</button> </form> <p>Your text: <span></span></p>

When need to pass information to somewhere else, like a database, on submit requires a page refresh. To prevent this refresh, you can use the preventDefault() method in JavaScript within the function that is invoked on the form submission.

// Function that runs when submit button is pressed
handleSubmit(event){
// Prevents the default behavior that includes page refresh
event.preventDefault();
// Rest of the code
}

Read about this event https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

If I understood properly, the solution doesn't necessarily lies in the React part of your system.

I think I understand well your problem: You have submitted a new entity, and after confirmation from the API you want to update the React UI with the newly-added entity.

Of course, there is no way to actually giving you React code for this since we don't know your page's component. Is it a table you want to update with the newly-added entity? Or is it maybe some list in card format? We don't know since you don't specify.

But let's rewind a bit: You need a proper API response before you can even think of updating your component/view/page/etc. with the new entity. Your API, upon successful addition of the entity, should respond with a copy of the added entity. Normally I create my REST API so that, on POST'ing of a new entity it responds with HTTP 201 CREATED plus a copy of the entity in the body.

Once you have a well-behaved REST API as described above, you may read the response body, parse it and send this new entity to your React component. Generally speaking, after parsing you would add the new entity to an array (if we're talking a list component of some sort here) that is passed to said list component in props .

I guess this is the best I can do for you right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM