0% found this document useful (0 votes)
25 views

RN Fundamentals

This document discusses ReactJS fundamentals including state, props, lifecycle methods, and class vs function components. It explains that class components can have state and lifecycle methods, while function components are stateless and receive data via props. Key lifecycle methods are described for mounting, updating, and unmounting components. Examples are provided for creating state, passing props, and composing reusable components.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

RN Fundamentals

This document discusses ReactJS fundamentals including state, props, lifecycle methods, and class vs function components. It explains that class components can have state and lifecycle methods, while function components are stateless and receive data via props. Key lifecycle methods are described for mounting, updating, and unmounting components. Examples are provided for creating state, passing props, and composing reusable components.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

ReactJS Fundamentals

ReactJS fundamentals - implementing state, props, and lifecycle


methods with React Native
ReactJS fundamentals

React class (stateful) vs function (stateless)

React / React Native components return React elements describing


what should appear on the screen.

class MyComponent extends React.Component { const MyComponent = () => (


render() { <Text>Hello World</Text>
return ( )
<Text>Hello World</Text>
)
}
}

<MyComponent />
ReactJS fundamentals
props

React / React Native components accept arbitrary inputs (called


"props") that can be used within the components.

class MyComponent extends React.Component { const MyComponent = (props) => (


render() { <Text>{props.name}</Text>
return ( )
<Text>{this.props.name}</Text>
)
}
}

<MyComponent name="Nader" />


ReactJS fundamentals
React class (stateful) vs function
(stateless) import React from 'react';
import { Text } from 'react-native';
stateful - class
A stateful component either contains state class App extends React.Component {
or needs to hook into lifecycle methods state = { name: 'Chris' }

state is data that is private and fully // lifecycle methods


controlled by the component.
render() {
return (
<Text>{this.state.name}</Text>
)
}
}

<App />
ReactJS fundamentals
React class (stateful) vs function
(stateless)
stateless - function

import React from 'react';


import { Text } from 'react-native';

const App = () => (


<Text>Hello World</Text>
);

<App />
ReactJS fundamentals
React class (stateful) vs function
(stateless)
stateless - es5 function declaration

import React from 'react';


import { Text } from 'react-native';

const App = function() {


return (
<Text>Hello World</Text>
);
};
ReactJS fundamentals

stateful vs stateless
stateless - function declaration hoisting

import React from 'react';


import { Text } from 'react-native';

function App() {
return (
<Text>Hello World</Text>
);
}
ReactJS fundamentals

stateful vs stateless
stateless - es2015 arrow function with explicit return

import React from 'react';


import { View, Text } from 'react-native';

const App = () => {


return (
<Text>Hello World</Text>
);
};
ReactJS fundamentals
lifecycle concepts

A stateful React component's lifecycle contains distinct phases for creation


and deletion. These are referred to as mounting and unmounting. You can
also think of them as "setup" and "cleanup".
ReactJS fundamentals
lifecycle concepts - mounting

When we create (or mount) a stateful React component, we


will trigger the component lifecycle which will create a new
React / React Native component
ReactJS fundamentals
lifecycle methods - in order of initialization
Class creation

Mounting
constructor() or property initializers
componentWillMount()
render()
componentDidMount()

read more about property initializers react documentation about property initializers
ReactJS fundamentals
mounting occurs and lifecycle
methods are triggered whenever import React from 'react';
import { View, Text } from 'react-native';
we create a React or React
class App extends React.Component {
Native class constructor() {}

componentWillMount() {}

componentDidMount() {}

render() {
return(
<View>
<Text>{this.state.name}</Text>
</View>
)
}
}
ReactJS fundamentals
lifecycle methods
Component destruction

Unmounting
componentWillUnmount()
ReactJS fundamentals
lifecycle methods
Updating component state and props

Updating state Updating props

shouldComponentUpdate() componentWillReceiveProps()

componentWillUpdate() shouldComponentUpdate()

render() componentWillUpdate()

componentDidUpdate() render()
componentDidUpdate()
ReactJS fundamentals

Creating state
stateful - state using property initializers to declare state

import React from 'react';


import { Text } from 'react-native';

class App extends React.Component {


state = { name: 'Chris' }

render() {
return(
<Text>{this.state.name}</Text>
)
}
}
ReactJS fundamentals

Creating state
stateful - using constructor to declare state
class Person extends React.Component {
constructor() {
super();
this.state = {
name: 'Chris',
};
}

render() {
return (
<View>
<Text>{this.state.name}</Text>
</View>
);
}
}
ReactJS fundamentals
composing reusable
components - class

class Name extends React.Component {


render() {
return <Text>Dave</Text>;
}
}

export default class extends React.Component {


render() {
return (
<Name />
);
}
}
ReactJS fundamentals
composing reusable
components - stateless function

const Name = () => <Text>Dave</Text>;

class App extends React.Component {


render() {
return (
<Name />
);
}
}
ReactJS fundamentals
props

<Person name="Chris" />

<App data={['a', 'b', 'c']} />

<User loggedIn={false} isActive />

<User loggedIn={false} isActive={true} />


ReactJS fundamentals

stateful vs stateless import React from 'react';


import { View, Text } from 'react-native';
props - receiving props in a class
class App extends Component {
render() {
return (
<Person name="Chris" />
)
}
}

class Person extends React.Component {


render() {
return(
<View>
<Text>{this.props.name}</Text>
</View>
)
}
}
ReactJS fundamentals

stateful vs stateless
props - receiving props in a stateless
import React from 'react';
function import { View, Text } from 'react-native';

class App extends Component {


render() {
return (
<Person name="Chris" />
)
}
};

const Person = (props) => (


<View>
<Text>{props.name}</Text>
</View>
);
ReactJS fundamentals

stateful vs stateless
import React from 'react';
props - destructuring in stateless import { View, Text } from 'react-native';
component
class App extends Component {
render() {
return (
<Person age={33} name="Chris" />
)
}
};

const Person = ({ name, age }) => (


<View>
<Text>{name} {age}</Text>
</View>
);
ReactJS fundamentals

stateful vs stateless
props - receiving child components as
props const RedContainer = (props) => (
<View style={{ backgroundColor: 'red' }}>
{ props.children }
</View>
);

class App extends React.Component {


render() {
return (
<RedContainer>
<Text>Hello World</Text>
</RedContainer>
);
}
}
ReactJS fundamentals

stateful vs stateless
Default props - class
class Person extends React.Component {
static defaultProps = {
name: 'Chris',
}

render () {
return (
<View>
<Text>{this.props.name}</Text>
</View>
)
}
};

export default App = () => <Person name="Jim" />;


ReactJS fundamentals

stateful vs stateless
Default props - stateless component

const Person = ({ name }) => (


<View>
<Text>{name}</Text>
</View>
);

Person.defaultProps = {
name: 'Mike'
};

export default App = () => <Person />;


ReactJS fundamentals

stateful vs stateless
propTypes

adding prop-types module


npm install --save prop-types
ReactJS fundamentals

stateful vs stateless import PropTypes from 'prop-types';

propTypes - class declaration class Person extends React.Component {


static propTypes = {
name: PropTypes.string.isRequired,
}

render() {
return (
<View>
<Text>{this.props.name}</Text>
</View>
);
}
};

class App extends React.Component {


render() {
return <Person name="Bob" />;
}
}
ReactJS fundamentals

stateful vs stateless import PropTypes from 'prop-types';

propTypes - stateless component


const Person = ({ name }) => (
<View>
<Text>{name}</Text>
</View>
);

Person.propTypes = {
name: PropTypes.string.isRequired,
};

class App extends React.Component {


static navigationOptions = {
title: 'Playground',
}
render() {
return <Person name="Bob" />;
}
}
ReactJS fundamentals

updating state
setState import React from 'react';
import { View, Text } from 'react-native';
setState enqueues changes to
the component state and tells class App extends React.Component {
React that this component and state = { name: 'Chris' }
its children need to be re-
rendered with the updated state updateName = () => {
this.setState({ name: 'Amanda' })
}

render() {
return(
<View>
<Text onPress={this.updateName}>{this.state.name}</Text>
</View>
)
}
}
ReactJS fundamentals

updating state
setState
setState enqueues changes to
the component state and tells
SetState
React that this component and shouldComponentUpdate()
its children need to be re-
rendered with the updated state componentWillUpdate()
render()
componentDidUpdate()
ReactJS fundamentals
import React from 'react';
setState import { View, Text } from 'react-native';

setState forces a rerendering of class App extends React.Component {


any component accessing the state = { name: 'Chris' }
changed state.
updateName = () => {
this.setState({ name: 'Amanda' })
}

render() {
return (
<Person name={this.state.name} onPress={this.updateName} />
)
}
}

const Person = ({ onPress, name }) => (


<View>
<Text onPress={onPress}>{name}</Text>
</View>
)
ReactJS fundamentals
setState
import React from 'react';
setState receives an optional import { View, Text } from 'react-native';
callback.
class App extends React.Component {
state = { name: 'Chris' }

updateName = () => {
this.setState({ name: 'Amanda' }, () => {
console.log('name is set!');
})
}

render() {
return (
<Text onPress={this.updateName}>{this.state.name}</Text>
)
}
}
ReactJS fundamentals
setState
State Updates May Be class App extends React.Component {
Asynchronous state = { value: 0 }

If you have multiple instances of increment = () => {


setState being called at once, it this.setState((state, props) => ({
may be a good idea to use the value: state.value + 1,
}));
setState callback. }
this.state may be updated
render() {
asynchronously, so you should return (
not rely on its value for <Text onPress={this.increment}>{this.state.value}</Text>
calculating the next state. )
}
}
ReactJS fundamentals
conditional rendering

state = { loggedIn: false }

login = () => {
this.setState({ loggedIn: true })
}

render() {
const { loggedIn } = this.state;

if (loggedIn) {
return <Text>Logged In</Text>
}

return <Text onPress={this.login}>Please Log In</Text>


}
ReactJS fundamentals
conditional rendering
logical and

state = { loggedIn: false }

login = () => {
this.setState({ loggedIn: true })
}

render() {
const { loggedIn } = this.state;

return (
<View>
{ loggedIn && <Text>Logged In</Text> }
{ !loggedIn && <Text onPress={this.login}>Please Log In</Text> }
</View>
);
}
ReactJS fundamentals
import {
conditional rendering Platform,
TouchableHighlight,
creating components TouchableNativeFeedback,
View,
on the fly. Text
} from 'react-native';

render() {
let Button = TouchableHighlight;

if (Platform.OS === 'android') {


Button = TouchableNativeFeedback;
}

return (
<View>
<Button onPress={console.log}>
<Text>Hello!</Text>
</Button>
</View>
);
}
ReactJS fundamentals
conditional rendering
filtering data in render.

state = {
sport: 'basketball'
}

render() {
let data = [{ name: 'chris', sport: 'baseball' }, { name: 'James', sport: 'basketball' }]

data = data.filter(d => d.sport === this.state.sport)

return (
<View>
{
data.map(d => <Text>{d.name}</Text>)
}
</View>
);
}
ReactJS fundamentals

creating variables in render - class

class extends React.Component {


state = {
sport: 'basketball'
}

render() {
const greeting = `${this.state.sport} is my favorite sport`;

return (
<Text>{greeting}</Text>
);
}
}
ReactJS fundamentals
creating variables in render -
stateless component

const App = ({ sport }) => {


const greeting = `${sport} is my favorite sport`;

return (
<Text>{greeting}</Text>
);
};
ReactJS fundamentals
updating with forceUpdate()

state = { loggedIn: false };

updateState = () => {
this.forceUpdate();
}

updateLoggedIn = () => {
this.state.loggedIn = true;
}

render() {
return (
<View>
<Text onPress={this.updateLoggedIn}>Log In</Text>
<Text onPress={this.updateState}>Force Update</Text>
{ this.state.loggedIn && <Text>Logged In</Text>}
</View>
);
}
ReactJS fundamentals
lifecycle -
componentWillMount
componenetWillMount is invoked
immediately before mounting componentWillMount() {
occurs. It is called before this.setState({
render(), therefore setting state startDateTime: new Date(Date.now())
synchronously in this method will });
}
not trigger a re-rendering.
render() {
Documentation recommends return (
using either constructor or <Text>{this.state.startDateTime.toLocaleString()}</Text>
property initializers instead. );
}
There is even a discussion about to
whether this method should be
deprecated.
ReactJS fundamentals
lifecycle -
componentDidMount
componenetDidMount is called
immediately after the render()
method has taken place.
componentDidMount() {
This is a great place to perform fetchFromApi()
Ajax calls, timeouts, or any other .then(data => this.setState({ data }))
}
operations.
This lifecycle method is used a lot in real
world applications.
ReactJS fundamentals
lifecycle -
componentDidMount
componenetDidMount is called
immediately after the render() componentDidMount() {
method has taken place. this.interval = setInterval(() => {
this.setState({
This is a great place to perform tick: this.state.tick + 1,
Ajax calls, timeouts, or any other });
operations. }, 1000);
}
This lifecycle method is used a lot in real
world applications. render() {
return (
<Text>{this.state.tick}</Text>
);
}
ReactJS fundamentals
lifecycle - componentWillUnmount
componenetWillUnmount is
componentDidMount() {
invoked immediately before a this.interval = setInterval(() => {
component is unmounted and this.setState({
destroyed. Perform any tick: this.state.tick + 1,
necessary cleanup in this });
}, 1000);
method, such as invalidating }
timers, canceling network
requests. componentWillUnmount() {
clearInterval(this.interval);
}

render() {
return (
<Text>{this.state.tick}</Text>
);
}
ReactJS fundamentals
lifecycle methods - called in
this order when setState is
called

state changes

shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
ReactJS fundamentals

lifecycle methods - called in


this order when props have
changed and when this is not
an initial rendering.

prop changes
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
ReactJS fundamentals
lifecycle - state = {
shouldComponentUpdate tick: 0,
}
returns boolean
shouldComponentUpdate is shouldComponentUpdate(nextProps, nextState) {
if (this.state.tick !== nextState.tick) {
always called before render and return true;
enables the component to figure }
out if a return false;
re-rendering is needed or can be }
skipped. tick = () => {
this.setState({
tick: this.state.tick + 1,
});
}

render() {
return (
<Text onPress={this.tick}>{this.state.tick}</Text>
);
}
ReactJS fundamentals
lifecycle -
componentWillReceiveProps
componentDidMount() {
componentWillReceiveProps is only this.fetchFromApi(this.props.id);
called when the props have changed }
and when this is not an initial rendering.
This method enables us to update the componentWillReceiveProps(nextProps) {
if (this.props.id !== nextProps.id) {
state depending on the existing and
this.fetchFromApi(nextProps.id);
upcoming props. }
}

fetchFromApi(id) {
fetch(`https://someurl/${id}`)
}

You might also like