4

I want to make shared component for all screen in react native. So I can share them between main components.

enter image description here

See my code below, everything works but the this.props.navigation.navigation.navigate('HireJob') not working.

MyCode :

export default class MyComponent extends Component {

    callAndPush = () =>{
      console.log('callAndPush');
      this.props.navigation.navigate('HireJob')
    }

    render() {
         return (
              <TouchableHighlight style = {{backgroundColor : 'red' , height : 30}} onPress = {() => this.callAndPush()}>
                <Text>Apple</Text>
              </TouchableHighlight>
         );
    }
}

Use of Component :

 render(){
    return (
      <View style = {styles.scrollSty}>
            <MyComponent></MyComponent>
     </View>
    );
 }
}
Val
  • 21,938
  • 10
  • 68
  • 86
Kirit Modi
  • 23,155
  • 15
  • 89
  • 112

2 Answers2

3

it works like this, bypassing navigation prop into MyComponent.

<MyComponent {...this.props} />
Val
  • 21,938
  • 10
  • 68
  • 86
1

Every component can be imported into other components, such as navigators. They import your scenes and navigate between them by sharing props.

To make a component and use it in different places simply create one:

export default class MyComponent extends React.Component {
    render() {
         return (
              <Text> This is a special component </Text>
         );
    }
}

And in your other classes use it like this:

import MyComponent from '../path/to/MyComponent';

class AnotherComponent extends React.Component {
    render() {
         return (
              <MyComponent />
         );
    }
}

Starting from React 0.14, you can create these easier using stateless components:

// A functional component using an ES2015 (ES6) arrow function:
const MyComponent = (props) => {
  return <Text> This is a special component </Text>
};

You can pass data using props if you like.

eden
  • 5,876
  • 2
  • 28
  • 43
  • Yes, I will added TouchableHighlight in MyComponent. and want to push another controller it give error. undefine is not an object. this2.props.navihation.navigate – Kirit Modi Aug 08 '17 at 11:07
  • Pass the function as a prop. I will update my answer tonighy – eden Aug 08 '17 at 11:21
  • Now updated code. in MyComponent have one function callAndPush and working fine but issue to push with stack navigation. – Kirit Modi Aug 08 '17 at 11:29
  • This is a different question. I have already explained for the first version. Mark it if this solved your problem at the first place – eden Aug 08 '17 at 18:45