React Native Pass Parent Method to Child Component - reactjs

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.

Related

How to passing refs to component in React

I have a data like this:
constructor(props) {
this.a = React.createRef();
this.b = React.createRef();
this.c = React.createRef();
}
setValue = (data = {}) => {
const {a='', b='', c=''} = data.constructor === ({}).constructor ? data : {};
this.a.current.setValue(a, data => {
this.b.current.setValue(data.b, data => {
this.c.current.setValue(data.c);
}
}
}
}
How could I passing that to my customized Component like this:
<CusComponent ref={this.a}>
Here is the function to get value in CusComponent:
value = function (a,b,c) {
if (arguments.length) {
if (a) {
this.setState({a}, () => {
this.value_a.value(a);
if (b) {
this.setState({b}, () => {
this.value_b.value(b);
if (c) {
this.setState({c}, () => {
this.value_c.value(c);
}
}
})
}
}
}
Thanks a lot!
Yes you can pass a ref down to a child component with:
<CusComponent ref={this.a}>
Make sure you create CusComponent with React.forwardRef because that creates an argument ref alongside props. This `ref you can directly bind to anything in your child component.
const CusComponent = React.forwardRef((props, ref) => (
<button ref={ref}>
{props.children}
</button>
));
You can read more in detail about this in the documentation.
If however both your parent and child component are class components then pass down the ref to CusComponent like so:
<CusComponent childref={this.a}>
Name the property something other than ref. Then you can access this ref in child component like below eg.
export default class CusComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div ref={this.props.childref}>Here</div>;
}
}

How to pass props or state from parent to child react in this format

I already have a foreknowledge of passing props or state from parent to child like this
class Parent extends React.Component{
state = {name: "parent-state"}
update = () => {
this.setState(state => state.name="example-state"})
}
render(){
return (
<ChildComponent {...this.state, update: this.update} />
)
}
Now my question is how to achieve this same feat in this format
class Parent extends React.Component{
state = {name: "parent-state"}
update = () => {
this.setState(state => state.name="example-state"})
}
render(){
return (
{this.props.children}
)
}
Do you mean something like this?
render() {
return React.cloneElement(this.props.children[0], {...this.state});
}

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);
}
};
}

ReactJS Using child props in parent class

I have a parent class which is using its child to render some Buttons out of the array 'days'. This is working fine so far. I use the handler to pass the handleClick() to the child. This also worked, without the if statement I get the return in console. What is wrong with my code or thinking for the if statement.
It should reply 'Hi 1' if I click on the Button with value days[0] = 1.
Parent:
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
days: [1,2,3]
}
}
handleClick() {
if(this.props.value === 1) {
return console.log('Hi 1')
}
}
render() {
return (
<div>
<div>
{this.state.days.map(item => <ButtonDays handler={ () => this.handleClick()} key={item} value={item} />)}
</div>
</div>
);
}
}
Child:
export default class ButtonDays extends React.Component {
render() {
return (
<Button onClick={this.props.handler}>{this.props.value}</Button>
);
}
}
In the following part of your parent component
handleClick() {
if(this.props.value === 1) {
return console.log('Hi 1')
}
}
You are checking for a props named value, but this props is only defined in your child component.
What you should do instead is passing the clicked value as a param of the handler function.
<Button onClick={() => this.props.handler(this.props.value)}>{this.props.value}</Button>
And then in your parent component:
handleClick(value) {
if(value === 1) {
return console.log('Hi 1')
}
}

Call child component function from parent

How do I call a child component function from the parent component? I've tried using refs but I can't get it to work. I get errors like, Cannot read property 'handleFilterByClass' of undefined.
Path: Parent Component
export default class StudentPage extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
newStudentUserCreated() {
console.log('newStudentUserCreated1');
this.refs.studentTable.handleTableUpdate();
}
render() {
return (
<div>
<StudentTable
studentUserProfiles={this.props.studentUserProfiles}
ref={this.studentTable}
/>
</div>
);
}
}
Path: StudentTable
export default class StudentTable extends React.Component {
constructor(props) {
super(props);
this.state = {
studentUserProfiles: props.studentUserProfiles,
};
this.handleTableUpdate = this.handleTableUpdate.bind(this);
}
handleTableUpdate = () => (event) => {
// Do stuff
}
render() {
return (
<div>
// stuff
</div>
);
}
}
UPDATE
Path StudentContainer
export default StudentContainer = withTracker(() => {
const addStudentContainerHandle = Meteor.subscribe('companyAdmin.addStudentContainer.userProfiles');
const loadingaddStudentContainerHandle = !addStudentContainerHandle.ready();
const studentUserProfiles = UserProfiles.find({ student: { $exists: true } }, { sort: { lastName: 1, firstName: 1 } }).fetch();
const studentUserProfilesExist = !loadingaddStudentContainerHandle && !!studentUserProfiles;
return {
studentUserProfiles: studentUserProfilesExist ? studentUserProfiles : [],
};
})(StudentPage);
My design here is: component (Child 1) creates a new studentProfile. Parent component is notified ... which then tells component (Child 2) to run a function to update the state of the table data.
I'm paraphrasing the OP's comment here but it seems the basic idea is for a child component to update a sibling child.
One solution is to use refs.
In this solution we have the Parent pass a function to ChildOne via props. When ChildOne calls this function the Parent then via a ref calls ChildTwo's updateTable function.
Docs: https://reactjs.org/docs/refs-and-the-dom.html
Demo (open console to view result): https://codesandbox.io/s/9102103xjo
class Parent extends React.Component {
constructor(props) {
super(props);
this.childTwo = React.createRef();
}
newUserCreated = () => {
this.childTwo.current.updateTable();
};
render() {
return (
<div className="App">
<ChildOne newUserCreated={this.newUserCreated} />
<ChildTwo ref={this.childTwo} />
</div>
);
}
}
class ChildOne extends React.Component {
handleSubmit = () => {
this.props.newUserCreated();
};
render() {
return <button onClick={this.handleSubmit}>Submit</button>;
}
}
class ChildTwo extends React.Component {
updateTable() {
console.log("Update Table");
}
render() {
return <div />;
}
}

Resources