Building Blocks of React-Native
Building Blocks of React-Native
Today, we will be discussing the 4-core concept of React-Native also knows as building blocks of React Native.
- component
- JSX
- props
- state
A component is a very basic element in react-native we can divide the large application into many small Components. This makes development fast and maintains the code very clear to understand. We will take an example to understand the component
Let's create a new ReactNative app following the below command.
- react-native init MyFirstApp
The above command will create a new react native app MyFirstApp.
Note: if react native is not installed then use npm install -g react-native-cli
to install it in your machine
Now use cd MyFirstApp and hit enter button
Now use npx react-native run-android command and hit the enter button,
Congratulation, Your First app is running now,
Note: You need to make sure emulator is installed or you are connected through USB in android phone or else you will get below error (snapshot)
Take a closer look on the return statement. such type of javascript syntax makes writing element more convenient
JSX
Take a look on below string
const element = <h1>Hello, world!</h1>;
Above code neither a string nor an HTML code
This is called JSX and we can say it is a syntax extension in javascript.
Take a look on below snapshot for JSX
props
Components are like javascript functions they accept input known as props and return React element describing what exactly should appear on the screen
Consider below code for props
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
state
Components Managing state is one of the most difficult concpets to grasp while learning React Native, as there are so many ways to do it. There are countless state management libraries on the npm registry - Such as Redux
And their endless libraries build on top of other state management libraries to simplify the original library itself e.g. Redux Easy
Take a look on below code for state
import React from 'react'
import { Text, Button } from 'react-native'
class ClickCounter extends React.Component {
state = {
counter: 0
}
render() {
const { counter } = this.state
return (
<>
<Text>{counter}</Text>
<Button onPress={() => { this.setState({ counter: counter + 1 }) }} title="Increment" />
<Button onPress={() => { this.setState({ counter: counter - 1 }) }} title="Decrement" />
</>
)
}
}
With ❤️ Happy Coding
Comments
Post a Comment