React updating prop and rendering based on boolean value - reactjs

I have a parent function component which has a boolean (which is set via child component and also used to render some container on parent component).
Is the below setup fine in terms of updating and dynamic rendering based on isSomeBoolean?
const [isSomeBoolean, setisSomeBoolean] = useState(true);
const updateIsSomeBoolean = (boolVal) => {
setisSomeBoolean(boolVal);
}
<ChildComp updateIsSomeBoolean={updateIsSomeBoolean} />
{isSomeBoolean && (
<div className="container">
....
</div>
)
}
In the child component, somewhere I invoke the parent function as below;
props.updateIsSomeBoolean(false);

Yes, Passing state and controller function to the child component is very normal in react.
But always keep in mind that changing state in parent component will render both components so keep the state near to component where is it required.
In your scenario, you're going in the right direction.

Related

What is a scalable way to retain state of a child component when the parent changes?

I have a design where a stateful GrandParent renders either ParentOne or ParentTwo, but both parents renders the same stateful Child component. When the parent component is changed, I want the state of Child to be retained (and its possibly stateful children).
I have created a tiny codepen to show what I mean, and I will also include the JavaScript for future reference in case it disappears:
https://codepen.io/chwallen/pen/WNJRKVB
function Child() {
const [myState, setMyState] = React.useState(false);
return (
<div>
<p>Is state modified: {myState.toString()}</p>
<button onClick={() => setMyState(true)}>Modify state</button>
</div>
);
}
function ParentOne({ children }) {
return (
<div className="parent-one">{children}</div>
);
}
function ParentTwo({ children }) {
return (
<div className="parent-two">{children}</div>
);
}
function GrandParent() {
const [isTrue, setIsTrue] = React.useState(true);
const Parent = isTrue ? ParentOne : ParentTwo;
return (
<div className="grand-parent">
<button onClick={() => setIsTrue(!isTrue)}>Toggle parent</button>
<Parent>
<Child />
</Parent>
</div>
);
}
ReactDOM.render(<GrandParent />, document.querySelector("#root"));
In this very simplified case, the solution is to move the Child state into the GrandParent. However, in the real case, there are more than one Child component which is dependent on a second state in GrandParent. Each of the child components may be stateful, and they in turn may contain stateful children. Moving all of that state to the GrandParent is not scalable. Additionally, I will lose the automagical state reset when the child, not parent, is unmounted (which is desirable) if the state is present in the GrandParent.
A second option would be to move the rendering of the Parent component as far down in the component tree as possible, i.e., each child would render the parent individually. This goes against DRY, and is really only moves the problem from GrandParent to the children.
One note: in this example, ParentOne and ParentTwo could easily be merged and controlled via props. In the real-world application however, these two components are vastly different and cannot be merged.
So my question is:
How can I, in a scalable way, retain the state for an arbitrary number of stateful children when their parent changes?
Store state in the GrandParent component, then pass it down or use context. I would put a context provider in the GrandParent, containing state and memoized control methods, and have a custom useMyContext type hook that I can use in the child components to reference/control state changes.

How to call functions in same level components in reactjs?

My root Component is App.js. It has many child components. But i have declare functions in child component and i need to access those function in equal level component in react js. [enter image description here][1]
this are the components hierarchy. i need to pass function from custom player to playbutton component
[1]: https://i.stack.imgur.com/XpEt1.png
Handle the state of the game in App.js. In their (custom player and playbutton component) parent. Pass the state function to them as props and handle the state there.
Ex:
Function App () {
const [SomeState, setSomeState] = setState()
Return
<>
<Button setSomeState={setSomeState}><\Button>
<Button2 setSomeState={setSomeState}><\Button2>
<\>
}
Those buttons handle the same state.
visit this site: https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component
You can pass state values to a child component as a prop, but you can also pass functions directly to the child component like this:
<ChildComponent
// The child component will access using actionName
actionName={this.actual_action_name}
/>
actionName is the name of the props that can be accessed by the child component. Once you trigger an action or pass the data from the child component, the same action's name will be accessed using this.props.action_name.
Let’s look at a simple example of passing the action to the child component.
<MyChildComponent
onSubmitData={this.onSubmitData}
/>

Is it possible to display props on a parent component?

Is there a way to DISPLAY props on parent component in React?
Is this similar to passing props from child component to parent component?
React and many other modern frameworks (like Vue) have what they call a top-down data flow:
This is commonly called a “top-down” or “unidirectional” data flow.
Any state is always owned by some specific component, and any data or
UI derived from that state can only affect components “below” them in
the tree.
If you imagine a component tree as a waterfall of props, each
component’s state is like an additional water source that joins it at
an arbitrary point but also flows down.
What you can do instead is supply the child component with an event listener and update the parent component's state accordingly.
const ParentComponent = () => {
const [parentState, setParentState] = useState(null)
return (
<ChildComponent
onTextChange={(newState) => setParentState(newState)}
value={parentState}
/>
)
}
const ChildComponent = ({ onTextChange, value }) => {
return <input type="text" value={value} onChange={onTextChange} />
}

REACT: How do you set a child component's state to its parent's state?

I would like the child component's state to update as the parent component's state updates. Any changes to parent state variables should be reflected in the child's state. How can I do this?
Thanks!
Edit:
My components are arranged in the following manner. I would like to access the parent's state from Child 2. By setting the Child 1 state to the parent's state, I will be able to do this.
Parent->Child 1->Child 2
You can pass the part of the parent state that you need as a prop to the child.
Then each time the parent state will change, the child will rerender with the correct value.
If you need to change the state from within the child, it depends on the behaviour you want.
You can make the child change the parent state by passing a callback function as a prop (you can pass the function used to change the state in the parent as a prop to the child)
Or you can make the child local state beeing reset to the parent state when it changes by listening to changes on the prop with a useEffect or ComponentDidUpdate.
useEffect(() => { setState(props.partOfparentState)},[props.partOfparentState])
or
ComponentDidUpdate(prevProps) {
if(previousProps.partOfParentState != props.partOfParentState) {
partOfParentStatethis.setState({state:props.parpartOfParentStatetOfParentState})
}
}
You could also want other behaviour which could be achieved with a more complex useEffect.
State And Props
React DOM compares the element and its children to the previous one,
and only applies the DOM updates necessary to bring the DOM to the
desired state.
the data flow in react is “unidirectional” or “top-down”,
Any state is always owned by some specific component, and any data or
UI derived from that state can only affect components “below” them in
the tree.
If you imagine a component tree as a waterfall of props, each
component’s state is like an additional water source that joins it at
an arbitrary point but also flows down.
This is why the state is often called local or encapsulated. It is not
accessible to any component other than the one that owns and sets it. #reactjs
Therefore, You Should pass the state to the child component, also known as prop.
Edit:
the hierarchy will be like this:
App(state - date) => Child1(prop date, passing the same prop to the next child) => Child2(getting date from his parent - Child1)
Example (based on Class Components):
<App>:
The root of the app.
<ClockList date={this.state.date} />
<ClockList>:
notice we are using props
<Clock date={this.props.date} />
<Clock>:
import React from "react";
const Clock = (props) => {
// Object Destructuring can also be done in the function itself.
const { date } = props;
return (
<div className="container">
<p>{date}</p>
</div>
);
};
export default Clock;

React. Recursive component

There is a component Child which is recursively invokes himself. Also the component has local state, for example, state = { isOpen: false }. This Child components wraps in a Parent component. So, we have one parent component with recursively generated child components (with their local state). The question is: How can I get access to specific Child component to invoke setState from the Parent component. Or how can I store recursively created components states inside Parent.
Any idea?
I did in this way:
const Asterics= ({i}) => [
<b>*</b>,
i>0 && <RAsterics i={i-1}/>
]
const RAsterics = (props)=><Asterics {...props}/>
export default Asterics
(React <16 instead)
const Asterics= ({i}) => <div>
<b>*</b>
{i>0 && <RAsterics i={i-1}/>}
</div>
const RAsterics = (props)=><Asterics {...props}/>
Then, whenever you need it:
<Asterics i={10}/>

Resources