i'm getting stuck , there is expenseForm (children) .if you look onSubmit takes an object "expense" why we need at this place .indeed we already dispatch some action .
<Expenseform onSubmit={expense => {
props.dispatch( AddExpenses (expense));
props.history.push("/");
}}
/>
props are designed in react to pass data from parents to children.
** change in props triggers a rerender of the component that the props are passed to, which refreshes your UI
if you are not passing data from parent to child, you don't need them. It depends on what you want to do with your component.
Related
I'm using React JS
I want to pass data from child component to another child component.
-App
-- Home
--- Filter ( Here is I need to to pass data from Filter component To Card component it's useState value)
--- Card ( Here I need to resive data )
Thre are two ways to solve this problem:
1 (I'd recommend for a smaller project): Just keep the state that needs to be shared in the parent component and pass it to the childs as a prop. You can update the state by creating a callback function in the parent component and calling it from the cild (after passing it as a prop aswell)
2: Use a state management libary like react-redux
I know that I will ask a question that brake some rules about the core/basic way to use React... but maybe with this example, someone helps me to solve the problem that I facing.
This is not the full code of my project, but show exactly the idea of my problem:
https://codesandbox.io/s/change-state-from-external-component-zi79e
The thing is I need to change a state from a child component from the parent component, but I don't want to run a render method in my parent or handle the state in the parent component.
Exists a way to achieve this? In my project, I have a parent that creates multiple generic children and it will be more difficult to handle this request.
And specifically, I need to change the state of one child (MyFirstChild), after another child (SecondChild) read the keystroke and run an API to get some values from my backend; after that, I need to send the change to "MyFirstChild" to change his state.
The parent component has ~50 child components and I blocked the re-render method (With the method shouldComponentUpdate)
The expected answer is: "It's not possible, or, you broke the good use of React"...
But, maybe using forwardRef or ref, or something else that I not see can help me to work around this...
To change the state of a child component from the parent without having to run a render method (in the parent): one possible solution would be to use Redux. With Redux from the parent you can dispatch an Action (execute an Action that changes the state of Redux).
And in the child component, you receive that part of the state that you change (it could be a string, object, etc) as a prop. So when it is changed from the parent, your child component will render again without having to run a render method in the parent.
https://react-redux.js.org/introduction/basic-tutorial
You could also use Context for the same purpose.
However, I saw your code example, I am not sure the exact reason of why you don't want to make a render in the parent, but the easiest solution for what you need would be to send the function that you want to execute in the parent as a prop and also the title.
If you want to change things from the parent, without re-rendering again with Redux, it would be something like this:
In the parent
const changeTitle = (newTitle) => {
this.props.setTitle(newTitle);
}
return (
<div className="App">
<ChildComponent />
</div>
);
const mapDispatchToProps = dispatch => ({
setTitle: newTitle => dispatch(setTitleACTION(newTitle)),
});
In the child
return (
<div>
<h1>
{this.props.title}
</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
const mapStateToProps = ({ title }) => ({
title,
});
export default connect(mapStateToProps, null)(ChildComponent);
Again if you make this with Redux, you can get the "title" prop from the Redux store, and in the parent, you will change that variable (calling to a Redux action) without rendering the parent again.
If you want to fire the event from the child component, you can dispatch the action from the child component or you could call a function (that you receive from props from the parent) and call that function whenever you need.
Can't we use props here for passing data instead of trying to manipulate state from outside of component?
Based on #david paley explanation...
If the only way to achieve this is using Redux, I post my solution (It's the same example, but, implementing Redux)... hope that works for anyone else.
https://codesandbox.io/s/change-state-from-external-component-redux-rmzes?file=/src/App.js
I have a parent component that fetches data in componentDidMount() hook. The state is setState()-d with this data. Then I pass the data to the child components as props and set their state based on these props. On the first render the props will be undefined because componentDidMount() hasn't executed yet. So, the child components get undefined props and the state is created with them. When the data fetches in componentDidMount() new props are passed to the child components, but the state is already created with undefined props and nothing changes. So, I am aware of two solutions now:
Use componentWillRecieveProps(). But this is now deprecated.
Use stateless child components. Pass the data to them as props from
the parent component and don't set a state(use the data from props),
and when the parent does a setState() in componentDidMount(), this
will cause a re-render to child components with new props and
everything works.
Now, what if I want to have stateful child components? I can't use the second method, and the first one is deprecated. What is the best solution to accomplish this?
static getDerivedStateFromProps(props, state)
is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
This method exists for rare use cases where the state depends on changes in props over time.
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.someValue!==prevState.someValue){
return { someState: nextProps.someValue};
}
else return null;
}
For more details enter link description here
You can read this blog post.
In short a better approach would be to use fully uncontrolled component with key.
Add a key to the child component based on data. If the data changes, the key changes and child component will re-mount.
Provide data as props to the child, use this props as default state of child component.
Here is a sandbox example
Consider using the replacement for componentDidReceiveProps, getDerivedStateFromProps, if you have state within a component which is informed by the values of the props it receives.
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
I'm new to React JS, I want to create a ToDo list app. I have App.js which is the main page and so I have created MainBlock component for App.js page which holds left and right side of my layout and in right side property it loads Form component which has input and button and saves input values to an array in state and in left side it loads List component which has a property named allTasks which prints all tasks.
My problem is how can I transfer allTasks state from Form Component to App.js to pass it to List component property?
In App.js :
<MainBlock
left={
<List allTasks={['خرید از فروشگاه', 'تعویض دستگیره درب منزل']} />}
right={
<Form />
} />
You can accomplish this by storing the tasks as state in the App component, and have Form pass up the state through a callback prop. This concept is called "lifting state up". Here's a guide about it: https://reactjs.org/docs/lifting-state-up.html
<MainBlock
left={
<List allTasks={this.state.allTasks} />
}
right={
<Form onSubmit={allTasks => this.setState({ allTasks })} />
}
/>
Let tasks be a state of the MainBlock component. Pass this state down to the List component.
Let the Form component expose a callback property (maybe onTaskCreated) which is invoked when user complete creating a new task.
Let MainBlock intercept onTaskCreated callbacks and update it's internal state with the new task, which causes it to re-render and thus passing down the new task list to the List component.
You are trying to achieve two way binding here. Unfortunately, React is a library that doesn't support two way binding by default.
You can only pass in the values from Parent to Child to Sub-Child. However, the reverse is not true.
In this case, you are trying to load props from Form to App that is from Child to Parent which is not possible.
You should make use of state containers such as Redux that overcomes this limitation by making the state of one component available to the other component.
You can store all your tasks in the state of the MainBlock component and pass functions to update the state by your form. Also, pass the state (tasks) of MainBlock to your List component. Updating your tasks to MainBlock will automatically pass the tasks to List. Later you could use a state management library like MobX and Redux.
It can be confusing passing data between components. Libraries like redux were created to make this "easier", but it can be done with simple React. To pass state information to children, you pass it into their props. To send data the other direction, you pass (from parent to child) a handler function that is called from the child and can affect the state of the parent (or be passed to it's parent) as needed.
I wrote a sample pen to help people wrap their heads around this. Hopefully it helps.
Something like:
<Child1 handleAdd={this.handleAdd.bind(this)}
handleSubtract={this.handleSubtract.bind(this)}
/>
calls in the parent and and is accessed in the child as:
<Button onClick={this.onAdd.bind(this)}>
add
</Button>
<Button onClick={this.props.handleSubtract.bind(this)}>
subtract
</Button>
Then there is a function in the parent called handleAdd that can affect the parent state.
I am trying to pass props to child component but the child is always receiving an empty.
Here's the code to make it clearer.
When I pass to child component a state, it works
Here's the working code:
render() {
return (
<div>
<PostList list={ this.state.posts }></PostList>
</div>
);
}
But in my case, I want pass the props from the redux state
Not working code:
render() {
return (
<div>
<PostList list={ this.props.posts }></PostList>
</div>
);
}
}
function mapStateToProps(state) {
return {
posts: state.posts.all,
postDetail: state.posts.post
}
}
Any ideas why the PostList is getting an empty object in the second case even though this.props.posts is not actually empty in the calling component?
Thanks
Install redux-devtools to see what your redux state actually looks like. For example, if you have used combineReducers(), then .posts may be prefixed with the name of a reducer.
Once you have verified the actual redux state, then double-check mapStateToProps to ensure you're referencing the correct state slice. In your question, I wonder if you may need to adjust it, but I cannot be sure without first knowing what your redux state is.
function mapStateToProps(state) {
return {
posts: state.posts
}
}
Please confirm what you are exporting. I assume your render() method is contained within a class? If so, ensure you export the result of connect(). Something like this:
export default connect(mapStateToProps, mapDispatchToProps)(MyReactClass)
Shouldn't you just attach to store in your child component? You can pass information where to attach if it's dynamic. Though passing store value by props sounds like a bad idea.
as for your example - this.props.posts props are intial values, re-render is not caused by props change inside your scope. Clearer explaination:
If parent changes props of child component - that cause re-rerender.
If parent changes it's own props then no re-rerender triggered. (this.props shouldn't be mutated)
If you want to cause an action use state - pass props to state. Then any manipulation on state will cause re-render of child.
<PostList list={ this.state.posts }></PostList>
Attaching to redux-state is triggered after your props are created therefore it's empty when child is called and (as said above) it won't trigger re-render.
edited:
Well, my answer was a bit chaotic. Let me try again.
Solution:
attach to store or wherever you get your data and pass this data to
this.state.posts = data. In constructor of your component set default state, like this.state = { posts: [] } (or whatever structure is required). In render() change your call for child into <PostList list={ this.state.posts }></PostList> and there you have it.
Notice:
Anyways since you're using redux I believe it would be better if you'd just attach to redux store inside your child component.