Skip to content Skip to sidebar Skip to footer

How To Access Ref Of A Component Through A Function In React Native?

I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like

Solution 1:

This is not good practice to setState of child component from parent component. I am assuming you want to set some value to your child component's state by trying this approach.

You can keep these values in your local state and pass it to props and your child component will re-render / get updated value there.

class Component {
  constructor() {
    this.state = {
      myValues: {
        component1: "abc",
        component2: "xyz",
        component3: "123",
      }
    }
  }

  myFunction(componentName, newValue) {
    this.setState({
      myValues: {
        ...this.state.myValues,
        [componentName]: newValue
      }
    })
  }

  render() {
    return (
      <View>
        <MyComponent value={this.state.myValues.component1} />
        <MyComponent value={this.state.myValues.component2} />
        <MyComponent value={this.state.myValues.component3} />
      </View>
    )
  }
};

Solution 2:

First make sur that MyComponent is a component and not a stateless Component, then, to change states, try this :

myFunction = (ref) => {
  ref.current.setState({ myState: myValue }
}

and of course , for it to work, your component need to be already mounts, If you try for example to call this in the constructor, it will not work


Solution 3:

Inside your component, in the componentDidMount function please add

componentDidMount() {
    this.props.refs(this) 
}

setState(key, value){
    this.setState({[key]:value})
}

and please change the ref param to refs

<MyComponent refs={component => this.myComponent1 = component} />

myFunction = (ref) => {
    ref.setState('myState', 'myValue')
}

Post a Comment for "How To Access Ref Of A Component Through A Function In React Native?"