I'm in the process of learning React. At the moment I have several components
chained as parent-child, communication across them is done easily with callbacks.
I have a table (react component) and a small modal ajax form (no react). When I receive the response (an item) from the server I would like to add the item to the table.
My main question is, is it possible to trigger a component state change from outside react (in this case on server response)?
component state best practice is to hold truly internal state data, not of interest outside component. If you must change a component from new external data use props , just change props from outside and the component rerender will react to changes.
Changes to the state also trigger a UI update. Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.
React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn't update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.
import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!
Can you trigger a component state change outside a component?
Yes. Heres a simple example
In your react component set up a globally available closure which will update it's state when the function is fired.
componentDidMount(){ globalVar.callback = (data) => { // `this` refers to our react component this.setState({...}); }; }
Then when your ajax'd response comes back you can fire the event with the returned data
globalVar.callback(data);
Or for something more robust, use a custom event or subscription
component
state best practice is to hold truly internal state
data, not of interest outside component. If you must change a component from new external data use props
, just change props
from outside and the component rerender will react to changes.
Based on new props
the component may use them on the rerender, or change state as did it in the constructor. The correct place to this task is in componentWillReceiveProps
, in this method you can change state from new props without get into an eternal loop.
UPDATE: from react 16.3 componentWillReceiveProps is deprecated and getDerivedStateFromProps must be used, with improved detection of bad use cases and side effects. See https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With