How to call functions in same level components in reactjs? - 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}
/>

Related

React JS - how to read specific attribute from a child JSX before mounting it to the DOM

What I need to achieve is to handle a specific attribute from one JSX component that I import to its parent component in a way that I will display here.
Child component returns JSX with 'someId' attribute:
return <h1 someId={123}>{title}</h1>
And the parent assigns this JSX to a variable and then needs to read this 'someId' attribute from it - before mounting the variable to the DOM:
let mySpecialChild = <Child title="Hello boys and girls!" />
let mySpecialChildId = mySpecialChild.someId
mySpecialChild.someId is now empty. I know it looks strange and against ReactJS rules but I need this for a very specific use case (in a loop, with additional conditions related to this child attribute). Here I created a sandbox for tests:
https://codesandbox.io/s/small-wood-jx33sz?file=/src/App.js
You can work around this issue by not using JSX to render that component, but directly calling it.
Disclaimer: You should not be using this approach.
If you want the returned DOM representation directly, you will have to call the Child component as a function instead of a JSX.
So if instead of
let mySpecialChild = <Child title="Hello boys and girls!" />
you do
let mySpecialChild = Child({title:"Hello boys and girls!"}),
then you can do let mySpecialChildId = mySpecialChild.props.someId;
Updated demo at: https://codesandbox.io/s/nameless-feather-fwdhs4
You should set a state on the parent component. codesandbox
Define a state which holds the id in the parent component.
Pass the function that sets the state (setSomeId) to the child component from the parent component.
Call setState function(setSomeId) when you want.
The state of parent component will update, so it will rerender with the new value of someId.
Edit:
Notice that the state setter function you pass will not change during renders. React docs state that:
React guarantees that setState function identity is stable and won’t change on re-renders.
There other ways for doing what you want:
useImperativeHandle: If you want to read the child id imperatively, you can pass a ref to the child component from the parent component and use useImperativeHandle hook inside the child component. You can call ref.current?.getId function from the parent component. Notice that if you want to display the id in the parent component, the parent component should be rerendered. So you will see the child id when you press the button that updates the state, and rerenders the parent component. codesandbox
Ref callback: If you don't need to render the value of someId from the child component and you want to call a function whenever the child id changes, you can pass a ref callback from the parent component to the child component. The callback gets called whenever the node is changed. You can access the property you want from the callback. If you want to render someId on the screen, you have to render the parent component. So you should set its value to state. (I changed someId to data-some-id because someId is not a valid prop on a DOM element. codesandbox.
You can access props as:
CODESANDBOX LINK
let mySpecialChild = <Child title="Hello boys and girls!" />;
console.log(mySpecialChild.props.title);
when you console.log mySpecialChild then It will log as:

React updating prop and rendering based on boolean value

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.

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 pass props between sibling components with hooks

I'm new to React and creating small app with REST Api to get some practice! So, when I clicking to pokeBox, in sider must be displaying details information about selected pokemon.
I attaching screenshot , how it looks now.
But I have no idea how I have to get constant with Pokemon.url.
It's my structure:
Wrapper (Parrent Component);
1.1. PokemonsList (Children);
1.1.1 GridCards (Children of PokemonsList)
1.2. About (Children)
So, I must get pokemon.url from GridCards and how I understanding, save in parrent component.
But, how is it was with functional component?
Using the hooks you can set a state in the parent component:
const [selectedPokemon, setSelectedPokemon] = useState()
and trigger a function when a new pokeBox is clicked in which to call setSelectedPokemon(pokemon.url).
In this way, you just have to pass selectedPokemon to the child component About in which you can render what you want based on the selectedPokemon value.
I suggest you put a piece of state in the parent component that you can pass to the about component (here you will save the data of the pokemon you want to display). Then you make a function to set data to the state you've just created and pass it to the PokemonList component so you can call that function when you click the name of the pokemon.
In wrapper:
this.state = {
selectedPokemon: {} // Pass this state to about comp as props
}
// Pass this function to pokemonList comp as props
setPokemon = (pokemon) => this.setState({ selectedPokemon: pokemon });

Prevent child from rerender when it updates parents state using parent method as prop in react native

I have a parent component and two child components. so i want to update second component when some action is performed in first component. Say I have Component1 and Component2, and a ParentComponent, so when I change state of ParentComponent from Component1 it changes the state in Component2 but also rerenders component1. I dont want to rerender component1. Tried to use callback but didnot help.
You can use memo to handle this scenario:
const MyComponent = React.memo(function MyComponent(props) {
/* only rerenders if props change */
});
Such component will only be re-rendered when there is a change in its own state or props.

Resources