Pass data from child component to another child - javascript

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

Related

Vue how to access props of parent component - the importer not a wrapper

Overall goal: from a child Vue component, get access to the component that it is imported and used within - which is not always the same as $parent. This should be done by only making changes within the child component (if possible).
We have PinButton Vue component meant to add a "pinning" functionality to other components. This component is used within many other components and we want to be able to access the parent props so they can be saved and rendered on a different page of "pinned content" by passing those props back into the parent component.
Note: I know this would be possible by manually passing the parent props down into the component (<pin-button :parent-props="$props" />), but we're trying to avoid having to do this every time the component is used.
A minimal reproduction of this with a single parent and child component will show that you can access parent props using $parent.$props. However, when the child component is nested as slot content of some other component within the parent, then the child will get the props of the wrapper component - not the component in which it is imported and actually used.
Sandbox reproduction - I want to get the props for ParentComponent from within ChildComponent. The expected value is shown by passing the props along (what I'm trying to avoid) and the actual value is the props of the SlotWrapper component, which doesn't import ChildComponent so I wouldn't consider it the true parent, but it is the direct parent element in the <template>
Update:
Seems like the suggested solution for "arbitrarily deep" access is provide/inject, but this would still seem to require changing all components that use the <pin-button />
To answer your question directly, you can access ParentComponent from ChildComponent via the "context" the component is rendered within:
// ChildComponent.vue
computed: {
expectedProps() {
return this.$vnode.context.$props
}
}
But this might be an "XY" kind of problem; I'm sure there's a better design solution for what you're trying to achieve.

How can i get boolean data from another component in vue js?

I have two Components.
In the second component, "date-detail-filter" I always keep track for boolean value, and want to access this data in my parent component.
do you know how to use $emit?
In your date-detail-filter component
you can add this to your method. this.$emit('your-event-name', 'your payload')
and in your main component.
<date-detail-filter #your-event-name="functionName()"/>
functionName(payload) {
your logic here to hide the caret
}
$emit is used to pass data from child component to parent component via event.

Is there a way to call a child-component's function from another child?

I'm contributing to an open-sourced React/Redux application built using ES6 JavaScript. I'm fairly new to React/Redux so I'm having some trouble.
I have a parent class that's rendering two different React components. The first component contains some input fields regarding events (called NewShift). The second component is a calendar that renders these events (called Index).
Once a user fills out the input fields and presses a button in the first component, I want to be able to re-render the calendar in the second component. If the re-render function is in the calendar component, how do I call it from the input fields component (both children).
React re-renders components whenever component state is changed. Should you be using just React, this would mean passing changed values up to the parent component's state to force a re-render.
However, Redux makes this easier on you, as it's 'Store' functions as a global state. You can force a re-render by changing appropriate variables within the store.
Given your situation: the button should get this within it's onClick attribute:
onClick={() => dispatchNewCalendarInfo(payload)}.
dispatchNewCalenderInfo should also be imported by the component:
import { dispatchNewCalendarInfo } from './redux/path/to/post/actions.js'; and connected to it: export default connect(()=>({}), { dispatchNewCalendarInfo })(Component);. Note, you need to also import connect from 'react-redux' for this.
And, of course, dispatchNewCalendarInfo should be present in the actions.js path, and accepted by the store reducer. This dispatch should alter information that the calendar is connected to, which will force it to update and re-paint.
If you're not using Redux there's another path you can take. Instead of having the function that takes input be in NewShift, have new shift receive the function as a prop from the parent.
So in your NewShift component you would have something like onClick={this.props.submitCalanderInfo()}
The submitCalanderInfo function would be part of the parent component. You would probably want this new info to be saved into the state of the parent component, and then then use that state to update the props on the calendar or Index component. So Index might look something like this:
<Index shiftData={this.state.shiftData} />

What's the best solution for re-rendering child components on props change in React?

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

How to transfer states among components?

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.

Categories

Resources