Once you install React Native, it provides you a lot of built-in components, “View” is the most fundamental component you can use, and there are others available to build your UI like Text, Image, and some basic others.
Let’s suppose you want to create an app with users feeds, you will definitely need a “Post” view that contains informations about each post, the user who posted it, his profil image and then maybe the text of his thoughts.
You probably will end up writing something like this to get it done:
<TouchableOpacity style={styles.postContainer} onPress={this.props.postPressed}>
<View style={styles.userInformations}>
<Image source={{uri: ‘http://cdn.yourserver.com/alex.jpg'}} />
<Text>Alex DuPont</Text>
</View>
<Text style={styles.status}>Hey, What’s up? </Text></TouchableOpacity>
We just created our own sauce of components, with TouchableOpacity as main element to add a tappable motion to the Post.
The idea here is to create a new component that renders your own puzzle of code and call it Post Component.
Create a new file under your “components” folder where we will define our class Post :
class Post extends Component {
constructor(props) {
super(props)
}
render() {
return (
<TouchableOpacity style={styles.postContainer} onPress={this.props.postPressed}>
<View style={styles.userInformations}>
<Image source={{uri: ‘this.props.post.userPicture’}} />
<Text>this.props.post.userName</Text>
</View>
<Text style={styles.status}>this.props.post.thoughts</Text></TouchableOpacity>
)
}
}
export default Post
In order to make it dynamic, we are using the props of the current instance.
Now, you can use the Post component wherever you want, the only missing part is the Post data that you need to pass as a property of the component after fetching some database or calling your API:
import Post from './components/Post.js'
...
<Post isMedia={false} data={this.state.post} />
Happy coding. 😃 💻