Passing Props to Screens in React Native

I have started to learn React Native and as always begin by creating reusable components. I learnt how you can pass and access props while creating custom components.

I want to create a base screen in React Native, which has common properties and all screens in my app can set, like a title for example.

Below I’m creating a new Screen for the home page of my app

class APCComponent extends Component {
    constructor(props) {
        super(props);
    }

    render() { //dummy function, will always get overridden in the child
        return (
            <View />
        );
    }
}

export default class Home extends APCComponent {
    //I somehow want to pass a string to the parent APCComponent
    //and want APCComponent use it to set the Header of the navigation

    constructor() {
        super({ title: 'Home' });
    }

    //Right now the following works, but in case I use a different type of Navigation,
    //I'll have to change all components. By just setting a string, I'm allowing my base
    //component to display the header
    static navigationOptions = { title: "Home" }; //from react-navigtion's StackNavigator

    render() {
        return <Button title="Sample Button" />;
    }
}

Thanks

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

class BaseComponent extends Component {
  render() {
    return (){
      <Header title={this.props.title} />
    }
  }
}

class HomeScreen extends Component {
  render() {
    return (){
      <BaseComponent title='this is your home screen' />
    }
  }
}

where Header component is also a separate reusable component.

you need to pass props(in our case ‘title’) from the upper level component to base level components like the above example.

Solution 2

In the constructor of HomeScreen, props should be able to passed to BaseComponent through

constructor(props) {
  super(props);
...

does it work for you?

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply