Reputation: 51
Thinking that I have a component:
<Component1>
<Component2 value={0}/>
{window.console.log(Component2.value)}
</Component1>
How may I do this window.console.log works, because I have a problem trying to reach that prop.
Upvotes: 1
Views: 18542
Reputation: 2922
Basically what you need to do is pass to your <Component2>
a callback function as a prop
that returns the value updated to your <Component1>
(I've made a little StackBlitz => https://stackblitz.com/edit/react-rym9h9?file=Component2.js), here you have the sample:
<Component1>:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Component2 from './Component2';
import './style.css';
class Component1 extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
getUpdatedValue = (updatedValue) => {
console.log('Here is your updated value: ', updatedValue);
};
render() {
return (
<div>
<Component2 value={0} returnUpdatedValue={this.getUpdatedValue} />
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
render(<Component1 />, document.getElementById('root'));
<Component2>:
import React, { Component } from 'react';
class Component2 extends Component {
componentDidMount() {
const { value, returnUpdatedValue } = this.props;
let updateValue = value + 100;
returnUpdatedValue(updateValue)
};
render() {
const { value } = this.props;
return (
<div>
<h1>{value}</h1>
</div>
);
}
}
export default Component2;
Upvotes: 0
Reputation: 326
Why don't you access that value from the state of the component1
?
class Component1 extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter() {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
}
render() {
return (
<View>
<Component2
incrementCounter={this.incrementCounter}
counter={this.state.counter} />
<Component3 counter={this.state.counter} />
</View>
)
}
}
Lastly inside the Component2
<button onClick={this.props.incrementCounter}>
click to increment counter
</button>
This is number one rule of the React, child components doesn't mutate data they speak to parent component through methods passed to them. This also makes data flow better, actually this is how you should be using React.
Upvotes: 0