Sunday, June 5, 2016

Views and Styling in React Native

React Native Views, JSX use and Styling :

This time we will cover the basic things needed  to create views and style components for mobile surfacely. Later on when we will  start to develop real functional app, then we can have deep knowledge about views. Before that have some overview and basic knowledge about Views and styling in React Native.

Rendering the  view is similar to React and we will feel easy if we are familiar to ReactJS and JSX.

React  component
render: function(){
return <div>hi ! </div>
}

React Native component
render: function(){
return <View>hi!</View>
}

When we write view in React , we use common HTML tags like <div>,<p>,<span>,etc. With React Native, all of these elements are replaced by platform specific React Components(as given below).
React    ReactNative
<div>    <View>
<span>    <Text>
<li><ul>   <ListView>
<img>    <Image>
There are other more components which we will discuss  later in each use.

On iOS, for instance, <View> component renders to a UIView, while on Andrioid it renders to a View.As components may vary from platform to platform, how we structure our React components becomes even more important when working in React Native.In React for web, we often have a mix of React components : some manage logic and their components, while other components render raw markup. If we want to mantain code and reuse it in React Native, it is somehow critical.

However the  components that render the view should be written sepreately like view.ios.js and view.android.js and the component that encapsulates the related logic can be reused. View component can be swapped out based on the platform.

Using JSX:

Just like in React, we use JSX(combining markup and JS into a single file) in React Native. JSX prioritizes the separation of concerns over the separation of technologies. In React Native, this is even more strictly enforced.
If you have never seen JSX before, do not worry , it is pretty simple and easy.
Let take a look in below example:

Pure Javascript component:

 var HelloMessage= React.createClass
({
    displayName: "HelloMessage",
  render: function render()
        {
return React.createElement
              (
"div",null,"Hello",this.props.name
              );
        }
});
React.render(React.createElement(HelloMessage,{name:"Kais"), mountNode);

JSX example:

var HelloMessage = React.createClass({
render: function(){
return <div>Hello {this.props.name}</div>;
}
});
React.render(<HelloMessage name="Kais"/>,mountNode);

Both will render following HTML on page:

<div>Hello Kais</div>

Styling:

React Native insists on the use of inline styles, which exits as JS objects.
Syntax looks like this:

//Define a style...
var style ={
backgroundColor: 'white',
fontSize: '16px'
};
//...and then apply it.
var tv=(
<Text style={style}>
A styled Text
</Text>);

** We will talk about styling more details in upcoming Posts. **

No comments:

Post a Comment