score:80
you can create a method in your parent component, pass it to child component and call it from props every time child's state changes, keeping the state in child component.
const enhancedtable = ({ parentcallback }) => {
const [count, setcount] = usestate(0);
return (
<button onclick={() => {
const newvalue = count + 1;
setcount(newvalue);
parentcallback(newvalue);
}}>
click me {count}
</button>
)
};
class pagecomponent extends react.component {
callback = (count) => {
// do something with value in parent component, like save to state
}
render() {
return (
<div classname="app">
<enhancedtable parentcallback={this.callback} />
<h2>count 0</h2>
(count should be updated from child)
</div>
)
}
}
score:-7
i've had to deal with a similar issue, and found another approach, using an object to reference the states between different functions, and in the same file.
import react, { usestate } from "react";
let mystate = {};
const grandparent = () => {
const [name, setname] = usestate("i'm grand parent");
mystate.name=name;
mystate.setname=setname;
return (
<>
<div>{name}</div>
<parent />
</>
);
};
export default grandparent;
const parent = () => {
return (
<>
<button onclick={() => mystate.setname("i'm from parent")}>
from parent
</button>
<child />
</>
);
};
const child = () => {
return (
<>
<button onclick={() => mystate.setname("i'm from child")}>
from child
</button>
</>
);
};
score:0
i had to do this in type script. the object-oriented aspect would need the dev to add this callback method as a field in the interface after inheriting from parent and the type of this prop would be function. i found this cool!
score:0
here's an another example of how we can pass state directly to the parent.
i modified a component example from react-select library which is a creatableselect component. the component was originally developed as class based component, i turned it into a functional component and changed state manipulation algorithm.
import react, {keyboardeventhandler} from 'react';
import creatableselect from 'react-select/creatable';
import { actionmeta, onchangevalue } from 'react-select';
const multiselecttextinput = (props) => {
const components = {
dropdownindicator: null,
};
interface option {
readonly label: string;
readonly value: string;
}
const createoption = (label: string) => ({
label,
value: label,
});
const handlechange = (value: onchangevalue<option, true>, actionmeta: actionmeta<option>) => {
console.group('value changed');
console.log(value);
console.log(`action: ${actionmeta.action}`);
console.groupend();
props.setvalue(value);
};
const handleinputchange = (inputvalue: string) => {
props.setinputvalue(inputvalue);
};
const handlekeydown: keyboardeventhandler<htmldivelement> = (event) => {
if (!props.inputvalue) return;
switch (event.key) {
case 'enter':
case 'tab':
console.group('value added');
console.log(props.value);
console.groupend();
props.setinputvalue('');
props.setvalue([...props.value, createoption(props.inputvalue)])
event.preventdefault();
}
};
return (
<creatableselect
id={props.id}
instanceid={props.id}
classname="w-100"
components={components}
inputvalue={props.inputvalue}
isclearable
ismulti
menuisopen={false}
onchange={handlechange}
oninputchange={handleinputchange}
onkeydown={handlekeydown}
placeholder="type something and press enter..."
value={props.value}
/>
);
};
export default multiselecttextinput;
i call it from the pages of my next js project like this
import multiselecttextinput from "../components/form/multiselect/multiselecttextinput";
const nccilite = () => {
const [value, setvalue] = usestate<any>([]);
const [inputvalue, setinputvalue] = usestate<any>('');
return (
<react.fragment>
....
<div classname="d-inline-flex col-md-9">
<multiselecttextinput
id="codes"
value={value}
setvalue={setvalue}
inputvalue={inputvalue}
setinputvalue={setinputvalue}
/>
</div>
...
</react.fragment>
);
};
as seen, the component modifies the page's (parent page's) state in which it is called.
score:0
if we have parent class component and child function component this is how we going to access child component usestates hooks value :--
class parent extends component() {
constructor(props){
super(props)
this.childcomponentref = react.createref()
}
render(){
console.log(' check child statevalue: ',
this.childcomponentref.current.info);
return (<> <childcomponent ref={this.childcomponentref} /> </>)
}
}
child component we would create using
react.forwardref((props, ref) => (<></>))
. and
useimperativehandle(ref, createhandle, [deps])
to customizes the instance value that is exposed to parent components
const childcomponent = react.forwardref((props, ref) => {
const [info, setinfo] = usestate("")
useeffect(() => {
axios.get("someurl").then((data)=>setinfo(data))
})
useimperativehandle(ref, () => {
return {
info: info
}
})
return (<> <h2> child component <h2> </>)
})
score:60
to make things super simple you can actually share state setters to children and now they have the access to set the state of its parent.
example: assume there are 4 components as below,
function app() {
return (
<div classname="app">
<grandparent />
</div>
);
}
const grandparent = () => {
const [name, setname] = usestate("i'm grand parent");
return (
<>
<div>{name}</div>
<parent setname={setname} />
</>
);
};
const parent = params => {
return (
<>
<button onclick={() => params.setname("i'm from parent")}>
from parent
</button>
<child setname={params.setname} />
</>
);
};
const child = params => {
return (
<>
<button onclick={() => params.setname("i'm from child")}>
from child
</button>
</>
);
};
so grandparent component has the actual state and by sharing the setter method (setname) to parent and child, they get the access to change the state of the grandparent.
you can find the working code in below sandbox, https://codesandbox.io/embed/async-fire-kl197
score:115
a common technique for these situations is to lift the state up to the first common ancestor of all the components that needs to use the state (i.e. the pagecomponent
in this case) and pass down the state and state-altering functions to the child components as props.
example
const { usestate } = react;
function pagecomponent() {
const [count, setcount] = usestate(0);
const increment = () => {
setcount(count + 1)
}
return (
<div classname="app">
<childcomponent onclick={increment} count={count} />
<h2>count {count}</h2>
(count should be updated from child)
</div>
);
}
const childcomponent = ({ onclick, count }) => {
return (
<button onclick={onclick}>
click me {count}
</button>
)
};
reactdom.render(<pagecomponent />, document.getelementbyid("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
Source: stackoverflow.com
Related Query
- React Hook : Send data from child to parent component
- How do I send data from child component to parent component in React
- Send Data From Parent Component To Child Component In React
- Send data from child component to parent component in react js
- Need to send the checkbox Filtered Data from Child Component to Parent Component : React Hooks, Redux
- react send data from child component to parent
- How to send array of objects data from child component to parent component and store in the parent object using react hooks?
- Updating Parent Component State from Child Component with UseState React Hook
- passing data from child to parent component - react - via callback function
- React | pass data from parent to child component
- Passing API data from parent container to child component in React
- How to send data from stateless child component to stateless parent component in react?
- How to update parent state from child component in React + send a paramater
- Send data from child to parent React
- React Send Data from Child to Parent with Typescript
- React router dom passing data from parent component to child router component does not pass the props.match
- React collect child component data on some event from the parent component
- Pass data from child to parent and to another child component React Js
- pass setState from parent to its child component using React Hook
- Passing data from child to parent component not working in react
- Share form data value from child component to parent component - React js
- How can I send data from a child to a parent functional component in ReactJS?
- How to send data from child component to parent component in reactjs
- Paasing data from a child class component to a parent functional component in react
- Can we Send data from nested child component to ancestor Parent component using useContext()?
- How to access data in a child react component from a parent react component
- send data from child to parent in react using props
- send data through onclick event from child to parent React js?
- Pass data via on click from child component to parent component react
- Unable to pass React form data from a Child component to a Parent Component
More Query from same tag
- Understanding React basic example
- useLocation can't be mocked with jest.fn() (while useHistory can be)
- How to access current state on Redux Toolkit on createAsyncThunk
- Can't pass relative img src route in React + Webpack
- most efficient way to set length restrictions on input type number in React
- Tag 'CreateStudent' expects at least '5' arguments, but the JSX factory 'React.createElement' provides at most '2'
- Node.js server overwritten entire DOM with React.JS
- x-axis label overwritten in svg graph
- What to set href to on a react component with an onclick
- Get document from collection using specific field in firestore
- Error in testing react/redux connected components using redux connected components approach
- In React, how do I name a field of my form that is part of an array?
- How to fetch json data from a url that requires an api key to access the data in reactjs?
- How can I use previous location to redirect user in react router v6?
- I am facing a very mysterious problem while sending data to the Firebase database
- How does a react app can be set up on server
- input value not exceeding on typing
- How to make checkmark stick to start of text? Tailwind
- Is there a way to pass props by goBack() in React?
- Problems updating single product price reactjs/redux
- React dynamic import based on the prop from parent
- Setting minimum image resolution in react-cropper
- Data in array items not being displayed on the screen in React
- How to make Node and React app to share classes
- ReactJS jsx load img URI from a string (doesn't work)
- how apply font feature settings in material UI makeStyles and change backgorundColor dynamically through props
- Gatsby - location.state 'Cannot read properties of null'
- React component not updating with current state but mapStateToProps is updating
- setState doesn't get updated the first time in react
- When importing from a library, Invariant failed: You should not use <Route> outside a <Router>