Store state within the React Router component? - reactjs

Ok, I'm pretty new to React in some ways and I am working on a simple react app that's 3 pages. I'm using react-router, partially so I can learn to use it.
On one page, I have a form that sets some state. The state obviously does not persist when you go to another route, because react-router renders a different component.
Solution #1
A solution is to have the main "App" component render one of the 3 pages/components (looking up the current route with params) and just store state there.
Solution #2
Another solution that seems obvious is storing the state in the Router component along with all the methods to update the state.
Then, I could just pass down the methods to update state to the components in the router. Seemed like a good idea, but I cannot seem to find anything online about anyone doing anything like that.
I see a lot of redux, but that's overkill for what I am doing.
So, is that possible? If it is, is there some reason that I cannot find anything about it? (Am I missing some terrible security thing or other gotchas that doing this would create.)

Instead of redux, i think you can also try react context. Ref
You can create a context in you App component and wrap your 3 page components in Context Provider to access the context. You can pass a map while creating a context, with values and setter,getter methods and use that map to change the values in your context map.
You can watch this talk for better understanding.
Hope this helps.

Redux is what you need. Check this below approach as well.
App component
class App extends Component {
state= {
test: 'test'
};
render() {
return (
<Route path="/" component={() => {<Home {...this.state.test}/>}/>
</div>
);
}
}

Related

How to re-render a component from another component in React

I'm new to react and here is my question , is there's a way to re-render a component from another component?
I'm using Redux and some of the global state is effecting component B .
But in my example component B is not re-rendered after some Redux state is changing from component C .
component C and B are not father/child to each other ,
is there a simple way to do it?
thanks
Every component will re-render if any of the states connected to it change. So in order to cause a re-render, simply include that state in both components connect function.
There is an option on how to re-render component inside component in React 16.x using Fragments. Documentation on this can be found here.
Short explanation: Your DOM will not be polluted with extra nodes, but will allow your app to use less memory which is always great. More in-depth explanation available here.
A frequent problem in Redux that causes this symptom is not using the spread operator to update the state object in your reducer. Try and return something like { ...state, newValue: 'food' }
You can use useNavigate and navigate to the same url you are on. For example, as the last line of your function, you can say navigate("/...your current url....")
window.location.reload() is not the best option everytime. It works on localhost, but for example on when you deploy it to the internet by using services such as "Netlify", it can can cause "not found url" error

React Router - What is the difference between Route children and component props

I've got some troubles understanding what's the diferrence between this:
<Route path="user/:id" component={UserComponent} />
and this:
<Route path="user/:id" children={<UserComponent/>} />
inside Switch component when using React Router.
In both cases those components will render if the url will look like this "/user/4322". I'm reading React Router documentation but I can't understand this use case correctly (https://reactrouter.com/core/api/Route/route-props)
Okay, I got it:
https://forum.freecodecamp.org/t/react-router-what-is-the-difference-between-route-children-and-component-props/429503
#DanCouper from FreeCodeCamp forum explained it perfectly:
the first one is if you want to mount a new component when the route
matches. This is what things most often look like: you have a set of
routes and they all open a new “screen”, last component unmounts, new
component mounts, everything gets blown away. It’s the simplest way to
do things.
second one is if you want something to render all the time and not
remount. So for example, as in the example in the docs, you have a set
of navigation links, and you want to animate between them on route
change. If you used component this wouldn’t work, because the new
component would mount every time and the animations wouldn’t happen.
But because children is used, can still have the URL change in the
browser but not have everything be blown away every time the URL
changes.
children (and render) are going to be more fiddly to use most of the
time, because they cater to less common scenarios (in children's case,
preventing new component creation every time routes change, allowing
the UI to dynamically change based on route).

What are the alternatives for high order component in react?

Coming with php background not sure how to implement a design with reusable code,
the problem:
we are creating a react/redux app with a lot of similar components that share a lot of functionality... I've read about HOC but was wondering if there are another solutions that would help in this situation!?
Component inheritance.
You can extend one component from some ComponentBase to share some functionality between them. But actually its different way from creating HOC. Hoc just allows you to pass some props to child, inheritance give you an ability to share methods and state.
There is something called function as child components (not sure if that's an official name but anyways)
The basic idea is that react accepts functions as child components, so for example instead of the react redux's connect HOC component you could do something like this
<Connect mapStateToProps={myMapper}>
{({ users, isLoading })} => {
//renders the user
}}
and the connect implementation is quite simple compared to a HOC.
render() {
return this.props.children(
this.props.mapStateToProps(this.state)
)
}
You can check a pretty interesting video about it here: https://www.youtube.com/watch?v=BcVAq3YFiuc

In the React, is the Route and Container 1: 1?

I think need your help.
Currently I am working with React.
I think in React, Container and Route are 1: 1. So when I do Router configuration with React. In a typical 'Redux' configuration, the Container(smart component) same to the number of pages in the route.
If I look at the implementation pattern of others, the Container does not just reflect the route.
Common There are many more cases than Route.
In the structure using 'Redux', is Container 1: 1 Route?
Also, Container does not seem to have an HTML Tag, is this correct?
This is not necessarily true, you may have a route that renders a component that doesn't have behaviour and because of that it'd still be a presentational component.
I'd recommend you to not get overwhelmed by the definitions of containers and component. Try to think a Route as just another component with the difference that when the path matches it will render the specified component (or in line function if you used the render property of the route.
Always start simple by creating components that are just functions which return content, and then as the requirements are changing start growing by declaring a class which extends Component and then start decoupling the returned elements into other components. Same thing with Redux, by default don't assume you always need behaviour/state so don't even connect the component and then start growing by adding state and then adding actions. But whenever you think your component has many responsibilities start the cycle again by decoupling into more components.

Accessing a component's state from another component

Would like a bit of knowledge gain with your help on this one. Just to clarify, I'm still educating myself with Reactjs.
I have two components, A and B. I need to access A's state from B. Is that possible?
var A = React.createClass({
getInitialState(){
return {foo: 'bar'}
},
...
});
var B = React.createClass({
getInitialState(){
return {x: 'y'}
},
render(){
var a = <A />;
var b = a.state.foo; // This was just a guess but I dont understand the docs for something like this.
return({b});
}
});
In B's component, how to render A's state, which is bar? I wish to have two separate components.
I have been reading about ref but still can't figure out how to accomplish what I want with refs.
React version: 0.14.3
Let's look at the purpose of state and props. A component's state is completely internal to a component. It is never known outside of the component and may/not be passed down to the children components (as props). Props on the other hand are explicitly public and are merely consumed by the component. They should be the only means of passing information down to a component.
While designing your components, always consider this that any data required by more than a single component cannot be a state of any one of them. React encourages unidirectional data flow and accessing state across different components violates that, thereby making your components difficult to reason with.
In your case, since B needs to know some information which A has, I suggest something like this -
A publishes this information to a Flux store at an appropriate time.
B has subscribed to the same Flux store, it gets notified of this
information and updates itself.
#HazardousS and #DERIIIFranz are wrong.
In reply to #HazardousS, just because you need data to go from one component to another does not warrant implementing Flux into your app. You always want to use props, then state, then... Flux. The lesson here is, "Only use Flux if you need to." Pete Hunt, an earlier Facebook-er who worked on React published this last week. It disspells a lot of the hype and misinformation in the React community: https://github.com/petehunt/react-howto
In regards to #DERIIIFranz about using Context: DO NOT USE CONTEXT. If you just click on the link the Facebook docs even have a warning for its own feature. It's something cute that the React docs does... they give you a lot of rope to hang yourself with.
It seems like you haven't gone through the React tutorials yet because you're asking basic questions about data messaging. This is something you need to understand in a fundamental way if you want to succeed in React. Put in the time, do the tutorials on the Official React docs page, and get familiar with the "React Way" of doing things. It's weird, and odd... but it'll click if you buckle down and sink in the time to learn the fundamentals.
We have to think of ways to make available the this.state.somevariable of <A/> inside <B/>.
If <A/> and <B/> are siblings of a common <Parent/>, the parent can change this state for both <A/> and <B/> and pass the changed state as this.props.statevariable to the children.
If <B/> can be a child of <A/>, <A/> can always pass its this.state.statevariable as props to <B/>.
If you go through the Flux Architecture, you can maintain these variables required for rendering inside the Stores and access these in as many components as you like.

Resources