[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]
by Zia Muhammad via Digital Information World
"Mr Branding" is a blog based on RSS for everything related to website branding and website design, it collects its posts from many sites in order to facilitate the updating to the latest technology.
To suggest any source, please contact me: Taha.baba@consultant.com
Redux is a library for state management that ensures that the application logic is well-organized and that apps work as expected. Redux makes it easy to understand your application's code regarding when, where, why, and how the state of the application is updated.
Redux is made up of the following key parts:
In this post, we'll look at each part of the Redux architecture in turn.
An action is a plain JavaScript object that has a type field and an optional payload. It can also be thought of to as an event that describes something that has happened.
const addTaskAction = {
type: 'task/taskAdded'
,payload: 'Laundry'
}
Action creators are just functions that create and return action objects.
const addTask = text => {
return {
type: 'task/taskAdded'',
payload: text
}
}
A reducer is also a function that receives the current state and an action object, updates the state if necessary, and returns the new state. A reducer is not allowed to modify the existing state; instead, it copies the existing state and changes the copied values. In other words, the reducer should be a pure function.
Here is an example.
const initialState = { value: 0 }
function counterReducer(state = initialState, action) {
// Check to see if the reducer cares about this action
if (action.type === 'counter/increment') {
// If so, make a copy of `state`
return {
...state,
// and update the copy with the new value
value: state.value + 1
}
}
// otherwise return the existing state unchanged
return state
}
A store is an object that stores the current state of a Redux application. You create the initial state of the store by passing a reducer to the configureStore functIon.
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({ reducer: counterReducer })
console.log(store.getState())
To get the current state of a store, use the getState() function as above.
dispatch() is a Redux store method and is used to update the state by passing an action object. Here, we create a task/taskAdded action with the addTask() action creator, then pass it to the dispatch() metdho.
store.dispatch(addTask('pick up laundry'))
Selectors are used for reading data from a store.
In this React Native Redux tutorial, you will develop an app that allows a user to choose from a given set of subjects. The app will contain two screens and you will also learn how to navigate between them using react-navigation.
Create a new project using Expo CLI tool
expo init ReduxApp
Currently, you have a single component App.js displaying a welcome message.
Create two new components in Home.js and Subjects.js The home component will be the first screen a user sees, and the subjects component will display all the subjects in our app. Copy the code from App.js and add it to Home.js and Subjects.js.
Modify Home.js and Subjects.js to use Home and Subjects instead of the App class.
//Home.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
class Home extends React.Component {
render() {
//...
}
}
// ...
export default Home;
Subects.js should look similar.
Currently, there is no way to navigate between the two screens. The stack navigator allows your app to transition between screens where each new screen is placed on top of a stack.
First, install @react-navigation/native and its dependencies.
npm install @react-navigation/native
For an Expo managed project, install the following.
expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view
Go to App.js and import react-native-gesture-handlerat the top. You also need to add NavigationContainer and createStackNavigator to App.js. Then, to add navigation capabilities, wrap the components inside the App class in a NavigationContainer component.
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
// ...
class App extends React.Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
/>
<Stack.Screen
name="Subjects"
component={Subjects}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
}
// ...
Now the navigator is aware of your screens, and you can provide links for transitioning between screens.
As we mentioned earlier, Redux is a state management tool, and you will use it to manage all the states of the application. Our application is a subject selector where the user chooses the subjects from a predefined list.
First, install the Redux packages.
npm install redux react-redux
A Redux app follows the following conditions:
For example, when a user clicks a button, the state is updated, and the UI renders the change based on the state.
The reducer will be responsible for keeping the state of the subjects at every point in time.
Create the file SubjectsReducer.js at the root level and add the following code.
import { combineReducers } from 'redux';
const INITIAL_STATE = {
current: [],
all_subjects: [
'Literature',
'Speech',
'Writing',
'Algebra',
'Geometry',
'Statistics',
'Chemisrty',
'Biology',
'Physics',
'Economics',
'Geography',
'History',
],
};
const subjectsReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
default:
return state
}
};
export default combineReducers({
subjects: subjectsReducer
});
In this file, you create an INITIAL_STATE variable with all the curriculum subjects and export the subjects reducer as a property called subjects. So far, the subjects reducer doesn't respond to any actions—the state can't change.
An action has a type and an optional payload. In this case, the type will be SELECT_SUBJECT, and the payload will be the array index of the subjects to be selected.
Create the SubjectsActions.js file at the root level and add the following code.
export const addSubject = subjectsIndex => (
{
type: 'SELECT_SUBJECT',
payload: subjectsIndex,
}
);
Now, we'll update the reducer to respond to this action.
// ...
const subjectsReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'SELECT_SUBJECT':
// copy the state
const { current, all_subjects,} = state;
//remove a subject from the all_subjects array
const addedSubject = all_subjects.splice(action.payload, 1);
// put subject in current array
current.push(addedSubject);
// update the redux state to reflect the change
const newState = { current, all_subjects };
//return new state
return newState;
default:
return state
}
};
// ...
Now, open App.js, and create a new store for the app using the createStore() function. We also make that store available to the components in our app by wrapping them in the <Provider> component. This will ensure that the store's state can be accessed by all of the child components.
import 'react-native-gesture-handler';
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import subjectsReducer from './SubjectsReducer';
import Home from './Home';
import Subjects from './Subjects';
// ... . rest of the code
const store = createStore(subjectsReducer);
class App extends React.Component {
// ...
render() {
return (
<Provider store={store}>
<NavigationContainer>
//.. rest of the code
</NavigationContainer>
</Provider>
)
}
}
Now let's see how to make state data available to components with the connect() function. To use connect(), we need to create a mapStateToProps function, which will maps the state from the store to the props in the two components.
Open Home.js, map the state, and render the values for the current subjects (which will be found in this.props.subjects.current). Also, add a button to navigate to the Subjects component.
import React from 'react';
import { connect } from 'react-redux';
import { StyleSheet, Text, View, Button } from 'react-native';
class Home extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>You have { this.props.all_subjects.current.length } subjects.</Text>
<Button
title="Select more subjects"
onPress={() =>
this.props.navigation.navigate('Subjects')
}
/>
</View>
);
}
}
const mapStateToProps = (state) => {
const { subjects } = state
return { subjects }
};
export default connect(mapStateToProps)(Home);
Similarly, we'll use connect in the Subjects.js file to map the state to the component properties.
import React from 'react';
import { connect } from 'react-redux';
import { StyleSheet, Text, View, Button } from 'react-native';
class Subjects extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>My Subjects!</Text>
/>
</View>
);
}
}
//...
const mapStateToProps = (state) => {
const { subjects } = state
return { subjects }
};
export default connect(mapStateToProps)(Subjects);
We'll also add the code to display all the subjects in the Subjects component and a button to navigate to the Home screen. You will also add a button that will add the addSubject action to Subject.js. Here's what the final render() method in Subject.js should look like this:
class Subject extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Select Subjects Below!</Text>
{
this.props.subjects.all_subjects.map((subject, index) => (
<Button
key={ subject }
title={ `Add ${ subject }` }
onPress={() =>
this.props.addSubject(index)
}
/>
))
}
<Button
title="Back to home"
onPress={() =>
this.props.navigation.navigate('Home')
}
/>
</View>
);
}
}
The final app should look like this.

Redux is a valuable tool, but it is only useful when used in the right way. Some of the situations where Redux might be helpful include code that is being worked on by many people or applications that contain large amounts of application state.
In this tutorial, you learned how to set up a React Native app using Redux.
CodeCanyon is a digital marketplace offers the best collection of React Native themes and templates. With a React Native app template, you can get started building your apps in the fastest time possible.

If you have trouble deciding which React Native template on CodeCanyon is right for you, this article should help:
The CSV (Comma Separated Values) file format is a popular way of exchanging data between applications.
In this quick tip, we’ll learn how JavaScript can help us visualize the data of a CSV file.
To begin with, let’s create a simple CSV file. To do this, we’ll take advantage of Mockaroo, an online test data generator. Here’s our file:

Now that we’ve generated the file, we’re ready to parse it and build an associated HTML table.
As a first step, we’ll use jQuery’s ajax function to retrieve the data from this file:
$.ajax({
url: 'csv_data.csv',
dataType: 'text',
}).done(successFunction);
Assuming the AJAX request is successful, the successFunction is executed. This function is responsible for parsing the returned data and transforming them into an HTML table:
function successFunction(data) {
var allRows = data.split(/\r?\n|\r/);
var table = '<table>';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr>';
} else {
table += '<tr>';
}
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
if (singleRow === 0) {
table += '<th>';
table += rowCells[rowCell];
table += '</th>';
} else {
table += '<td>';
table += rowCells[rowCell];
table += '</td>';
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</tr>';
}
}
table += '</tbody>';
table += '</table>';
$('body').append(table);
}
So, the idea is to convert each of the CSV rows into a table row. With that in mind, let’s briefly explain how the code above works:
Furthermore, to get a better understanding of this code, consider the following visualization:

At this point, it’s important to clarify why we used the /\r?\n|\r/ regex to split the CSV rows.
As you probably already know, there are different representations of a newline across operating systems. For example, on Windows platforms the characters representing a newline are \r\n. That said, by using the regex above, we’re able to match all those possible representations.
In addition, most text editors allow us to choose the format for a newline. Take, for instance, Notepad++. In this editor, we can specify the desired format for a document by navigating to this path:

To illustrate it, consider our file. Depending on the format we choose, it would look like this:

Before we look at the resulting table, let’s add a few basic styles to it:
table {
margin: 0 auto;
text-align: center;
border-collapse: collapse;
border: 1px solid #d4d4d4;
}
tr:nth-child(even) {
background: #d4d4d4;
}
th, td {
padding: 10px 30px;
}
th {
border-bottom: 1px solid #d4d4d4;
}
Here’s the generated table:

In this section, we’ll see how you can use the PapaParse library to parse a CSV file in the blink of eye! PapaParse is a really powerful CSV parser which provides you a lot of configuration options and you could use it for really big CSV files as well.
The PapaParse library is available on npm, and if you don’t want to use npm, you can download the official PapaParse nmp package from unpkg instead.
The following example demonstrates how easy it is to parse a CSV string.
var results = Papa.parse(data); // data is a CSV string
The results variable holds the following contents.

As you can see, Results.data holds an array of all the rows. If there are any errors during parsing, they will be in Results.errors. Finally, you can use Results.meta to access meta information about the CSV string.
On the other hand, if you want to directly parse a local CSV file you can pass a JavaScript File object:
Papa.parse(fileInput.files[0], {
complete: function(results) {
console.log(results);
}
});
And you can also pass in the URL to a remote CSV file:
Papa.parse(url, {
download: true,
complete: function(results) {
console.log(results);
}
});
Apart from basic parsing, PapaParse provides a lot of other features like:
I encourage you to explore this library since it’s really powerful and easy-to-use!
In this short article, we went through the process of converting a CSV file into an HTML table. Of course, we could have used a web-based tool for this conversion, yet I think that it’s always more challenging to achieve this by writing your own code.
Fun launching soon page (built using Webflow) announcing the upcoming Gowalla augmented reality social game.