Reactjs Passing props from the child - reactjs

I got the property from the child but how can I pass to the parent?
in parent.js
<Child childId={() => this.getchildId()} />
getchildId = (id) => {
// do something
console.log(id) // return undefined
}
in child.js
const id = "something";
<Item itemid={this.getId(id)} />
getId = (id) => {
console.log(id); // return "something"
this.props.childId(id)
}
Update!
It works with
in parent.js
<Child childId={this.getchildId} />
Now the problem is they are keep being called...

// in parent
getchildId = (id) => {
// do something
console.log(id) // return undefined
}
<FirstChild logChildId={this.getchildId}
// in FirstChild
<SecondChild logChildId={props.logChildId} />
// in SecondChild
<button onClick={() => props.logChildId("test")}>
click me
</button>
so it's just passing down the function pointer via props
Can you show the code for your <Item /> component? make sure that the function isn't directly invoked and only referenced by arrow function just as I pointed out in second child, or via method if you are writing a class function
// in SecondChild
handleLogChildId = (id) => {
const { logChildId } = this.props
logChildId(id)
}
<button onClick={this.handleLogChildId("test")}>
click me
</button>

<Child childId={this.getchildId} />
getchildId = (id) => {
// do something
console.log(id) // return undefined
}
In parent.js just pass the function reference.

Passing anything from child to parent is very simple via functions.
let assume you have a parent like this
class Parent extends Component {
constructor(props){
this._getProps = this._getProps.bind(this);
}
_getProps(data) { // Here you will receive the props data from child component.
console.log(data);
}
render(){
return (
<Child getProps = {this._getProps}/>
);
}
}
class Child extends Component {
constructor(props){
this._sendProps = this._sendProps.bind(this);
}
_sendProps(data) {
this.props.getProps(data); // This will send your props data to parent function.
}
render(){
return (
<div> </div>
);
}
}

Related

passing ref from parent functional component to child class component to call a function in child class component

I have a parent functonal component:
const parentFunc = () => {
if (ref.current) {
ref.current.getKinList();
}
};
<TouchableOpacity
onPress={() => {parentFunc()}
>
<Text>click</Text>
</TouchableOpacity>
<ChildComponent
ref={ref}
/>
child class component:
componentDidMount = () => {
this.ref = { current: { function2 : this.function2 } };
};
function2 = () => {
console.log('called from child');
};
function2 is not getting called from parent component.
There are solutions available, but I am not able to figure out where I am going wrong.
When I consoled ref.current in parentFunc it is coming as undefined
You can do something like this:
export default function App() {
const actions = React.useRef({
setMyAction: (f) => {
actions.current.myAction = f;
}
});
return (
<div>
<div onClick={() => actions.current.myAction()}>click</div>
<ChildComponent actions={actions.current} />
</div>
);
}
const ChildComponent = ({ actions }) => {
actions.setMyAction(() => {
console.log("called from child");
});
return null;
};
Working example
Also keep in mind that ref is a special name, not a usual property.

How can I pass a prop from child to parent component

How can I pass a prop (when modified) from Child Component to a Parent Component.
Some Details :
I am working on an existing codebase where I have Parent Component embedded in
'unstated.Container' and a separate Child Component , where I am trying to add a button. When
a user clicks this button some value gets updated , which needs to be passed to the Parent
component .
Thank you.
import {Container} from 'unstated';
class DelContainer extends Container{
state = { sortAsc : true, notified : null}
setVal = async (Id, value) => { console.log (`Id : ${Id}); console.log('value: ${value}); }
}
//Child Component (Separate file)
const ChildItems = (props) => {
const [some_value ] = props;
const [some_color, setColor] = useState(" ");
const MarkIt = ({some_value})
{
some_value = this.props.some_value; //ISSUE HERE
}
return (
<IconButton >
<StarOutlinedIcon onClick = {MarkIt} style={{color: `${some_color}`}}/>
</IconButton>
);
}
//Parent Component (Separate file)
import {Subscribe} from 'unstated';
const DelList = (props) => {
return(
<Subscribe to ={[DelContainer]}>
{
(delStore) => {
const[person, isLoading] = delStore.state;
return(
<div>
<List className = {props.className} isLoading = {Loading}>
{
isLoading && person
.map((person, index)=>{
return <ChildItem key={index}
person = {person}
some_value = {delStore.MarkIt(some_value)};
}
}
</List<
</div>
)
}
}
);
}
Read this :
How to update parent's state in React?
Reactjs DOCS:
https://reactjs.org/docs/lifting-state-up.html
class Parent extends React.Component {
liftStateHander=()=> {
this.setState({
name:"John"
})
}
render() {
return <Child handler={this.liftStateHander} />
}
}
class Child extends React.Component {
render() {
return (
<button onClick={this.props.handler}>
Click For Change State Parent
</button>
)
}
}

React passed data from child to parent not logging in parent

I tried to pass data from a child component to it's parent but it isn't showing in the parent component.
In parent component I want to display the duration of a service that is selected in the child component.
In the child component I can log the selected service but it isn't passing to its parent:
Parent component:
class CalenderModal extends React.Component {
state={selectedService:[]}
// handover of child data to parent
handleServiceSelect = (selectedServiceObj) => {
this.setState({selectedService: selectedServiceObj});
console.log('inside CalendarModal:', this.state.selectedService)
}
handleRemove = () => {
this.props.onRemove();
}
handleSave = () => {
const fullname = this.fullname.value;
const phone = this.phone.value;
this.props.onSave({
fullname,
phone,
});
}
render() {
return (
<div className="customModal">
<div>Choose service you want to schedule:</div>
/// child component
<ServiceSearch onServiceSelect={()=> this.handleServiceSelect}/>
<div>{this.state.selectedService.duration} hours</div>
<button className="customModal__button customModal__button_example" onClick={this.handleSave}>{action}</button>
</div>
);
}
}
export default CalenderModal;
Child component:
class ServiceList extends Component {
constructor(props) {
super(props);
}
servicesToRender=[]
handleServiceSelect = (event) => {
var selectedServiceId = event.target.value;
var selectedService = this.servicesToRender.find(({id})=> id === selectedServiceId )
console.log("inside Service search:",selectedService)
this.props.onServiceSelect(selectedService);
}
render() {
const FEED_QUERY = gql`
{
servicefeed {
id
name
cost
duration
}
}
`
return (
<Query query={FEED_QUERY} >
{({ loading, error, data }) => {
if (loading) return <div>Fetching</div>
if (error) return <div>Error</div>
this.servicesToRender= data.servicefeed
// const servicesToRender = data.servicefeed
return (
<React.Fragment>
<label class="my-1 mr-2" for="inlineFormCustomSelectPref">choose service:</label>
<select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" onChange={this.handleServiceSelect}>
{this.servicesToRender.map(service => <ServiceSearchOption key={service.id} service={service} />)}
</select>
</React.Fragment>
)
}}
</Query>
)
}
}
export default ServiceList
I'm not sure what I'm missing here.
You haven't called the function in parent when passing it as props and using arrow function inline. The correct ways is below
<ServiceSearch onServiceSelect={()=> this.handleServiceSelect()}/>
However, you could have simply passed the function reference without an arrow function since the handleServiceSelect is already and arrow function and will have function binding
<ServiceSearch onServiceSelect={this.handleServiceSelect}/>

ReactJS: Trigger event from child in parent component

i have two components: 1.Parent 2.Child
there is an event in child component called onChange() which return a value.
i want to receive the value which was returned from OnChange() in componentDidMount() in parent component.
Example:
class Parent extends PureComponent {
componentDidMount() {
let value = CHILD.onChange(); //triggered when ever onChange()
}
render(){
return(
<Child />
)
}
}
const Child = () => {
const onChange = () => {
const value = 1
return value;
};
}
class Parent extends PureComponent {
handleChildChange = value => {
//Do your stuff with value, pass it to the state and take it from there if you like
}
render(){
return(
<Child handleChange={this.handleChildChange} />
)
}
}
const Child = (props) => {
const onChange = () => {
value = 1
props.handleChange(value);
}
};
}

React Native Pass Parent Method to Child Component

I am trying to pass method from my parent component to child component. My code is correct i think but still it shows the error undefined is not an object(evaluating '_this2.props.updateData') . I don't know whats the issue because i searched the internet a lot and everyone is passing props to child like this. Kindly tell what am i missing
Parent:
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={val => this.updateData(val)} />
);
}
Child:
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick()}>Test</button>
);
}
}
`class Child extends React.Component {
handleClick = () => {
const passedData = 'child data'
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}`
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
}
render() {
return (
<Child updateData={this.updateData} />
);
}
}
and child component: `
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}
`
You need to pass the function directly, not as a callback
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={this.updateData} />
);
}
I think you need to pass a function like this. Check out this solution.

Resources