Introduction of React Native UUID
UUID stands for Universal Unique Identifier. It has a 128 bit number for a unique identification of any object or entity. A Universal Unique Identifier depends on the combination of the different components which ensures its uniqueness. Any UUID which is guaranteed contains three categories of elements. Firstly, it has the reference to the host’s address which has generated the UUID. Secondly, it contains the specific time of the generation and lastly, it has a combination of random characters or numbers. In this article, we will go through an example which uses the universal unique identifier for identifying the unique components.
Syntax:
Syntax of generating UUIDs in react native:
import uuid from "react-native-uuid";
uuid.v1();
uuid.v4();
Working of React Native UUID with Examples
Universal Unique Identifiers of the First Version is a combination of three components as discussed above. The address of the host computer, the specific time and date of the UUID generation and a combination of random characters or numbers to make sure that the UUID becomes unique. In the case of UUID v4 all of its components are generated randomly without any logic. There are around 2Ʌ128 possible combinations of UUIDs which increases the possibility of the UUID’s uniqueness.
1. Tasks List/ Notes list using
In the example below, we have imported uuidfrom react-native-uuid in the Addtodo.js file and UUID helps in making the unique ID for every task stored in the and it’s been used as:
this.state = {
id: uuid.v1(),
text: "",
isCompleted: false
};
And also as:
let newTodo = {
id: uuid.v1(),
text: this.state.text,
isCompleted: false
};
The files used to implement the code below are:
AddTodo.js
import React
, { Component } from "react";
import { connect } from "react-redux";
import { AddTodoAction } from "./action";
import uuid from "react-native-uuid";
class AddTodo extends Component {
constructor(props) {
super(props);
this.state = {
id: uuid.v1(),
text: "",
isCompleted: false
};
this.onInputChangeHandler = this.onInputChangeHandler.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onInputChangeHandler(ev) {
let text = ev.target.value;
this.setState({ text });
}
onSubmit() {
let newTodo = {
id: uuid.v1(),
text: this.state.text,
isCompleted: false
};
this.setState({ text: "" });
this.props.dispatch(AddTodoAction(newTodo));
}
render() {
return (
<div className="add-todo">
<input
type="text"
value={this.state.text}
onChange={this.onInputChangeHandler}
name="todo"
/>
<button onClick={this.onSubmit}>Click to Add</button>
</div>
);
}
}
constConnectAddTodo = connect()(AddTodo);
export default ConnectAddTodo;
FilterOptions.js
import React from "react";
constFilterOptions = ({ items, onSelect, selectedFilter }) => {
constonChangeHandler = ev => {
onSelect(ev.target.value);
};
return (
<select value={selectedFilter} onChange={onChangeHandler}>
{items.map((item, index) => (
<option key={index} value={item.type}>
{item.display_name}
</option>
))}
</select>
);
};
export default FilterOptions;
Root.js
import React from "react";
import { Provider } from "react-redux";
import { BrowserRouter as Router
, Route } from "react-router-dom";
import TodoApp from "./TodoApp";
const Root = (
{
store
}
) => {
return (
<div className="App">
<Provider store={store}>
<Router>
<Route path="/" component={TodoApp} />
</Router>
</Provider>
</div>
);
};
export default Root;
TodoApp.css
.todo-app {
border: 10px solid #d92e8c;
border-bottom-left-radius: 50%;
border-top-right-radius: 50%;
}
.todo-wrapper {
float: left;
}
.todo-list {
float: right;
border: 10px solid #78db14;
min-height: 250px;
width: 550px;
}
.todo-list ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}
.todo-list ul .each-todo {
width: 250px;
float: left;
padding: 12px;
}
.todo-list ul li {
float: left;
margin-left: 12px;
}
.todo-list ul input {
float: centre;
}
.todo-list ul .removeBtn {
cursor: pointer;
}
.add-todo {
float: left;
border: 10px solid #fac12f;
min-height: 150px;
width: 400px;
padding: 15px;
border-bottom-left-radius: 50%;
border-bottom-right-radius: 50%;
border-top-left-radius: 50%;
border-top-right-radius: 50%;
}
.add-todo input {
float: centre;
height: 10px;
width: 150px;
}
.add-todo button {
margin-left: 1px;
}
TodoApp.js
import React from "react";
import TodoList from "./TodoList";
import AddTodo from "./AddTodo";
import TodoFilters from "./TodoFilters";
import "./TodoApp.css";
constTodoApp = () => {
return (
<div className="todo-app">
<h1>Notes Application</h1>
<div className="todo-wrapper">
<TodoFilters />
<TodoList />
<AddTodo />
</div>
</div>
);
};
export default TodoApp;
TodoFilters.js
import React from "react";
import { connect } from "react-redux";
import FilterOptions from "./FilterOptions";
import { showTodoFilterAction } from "./action";
constTodoFilters = props => {
constonSelectHandler = value => {
console.log("showTodoFilterAction", showTodoFilterAction(value));
props.dispatch(showTodoFilterAction(value));
};
console.log("props", props);
const filters = [
{
type: "ALL",
display_name: "All Tasks"
},
{
type: "COMPLETED",
display_name: "Completed Tasks"
},
{
type: "ACTIVE",
display_name: "Active Tasks"
}
];
return (
<div>
<FilterOptions items={filters} {...props} onSelect={onSelectHandler} />
</div>
);
};
constmapStateToProps = state => {
console.log(state);
return {
selectedFilter: state.todoFilters.filter
};
};
constConnectTodoFilters = connect(mapStateToProps)(TodoFilters);
export default ConnectTodoFilters;
TodoList.js
import React from "react";
import { connect } from "react-redux";
import { DeleteTodoAction
, updateTodoAction } from "./action";
import selectTodos from "./todos";
constTodoList = props => {
console.log("TodoList", props);
constonDeleteHandler = id => {
props.dispatch(DeleteTodoAction(id));
};
constonCompleteTodoHandler = id => {
props.dispatch(updateTodoAction(id));
};
return (
<div className="todo-list">
<h1>Your Tasks Appears Here</h1>
<ul>
{props.todos.map(todo => {
return (
<div key={todo.id} className="each-todo">
<input
id="todo,id"
checked={todo.isCompleted}
onClick={ev => {
onCompleteTodoHandler(todo.id);
}}
type="checkbox"
/>
<li
style={{
textDecoration: todo.isCompleted ? "line-through" : "none"
}}
>
{todo.text}
</li>
<span
className="removeBtn"
onClick={() => {
onDeleteHandler(todo.id);
}}
>
x
</span>
</div>
);
})}
</ul>
</div>
);
};
constmapStateToProps = state => {
console.log("mapStateToProps", state);
return {
todos: selectTodos(state.todos, state.todoFilters)
};
};
constConnectTodoList = connect(mapStateToProps)(TodoList);
export default ConnectTodoList;
action.js
constAddTodoAction = todo => (
{
type: "ADD_TODO", todo
}
);
constDeleteTodoAction = todoId => (
{
type: "REMOVE_TODO", todoId
}
);
constupdateTodoAction = todoId =>({ type: "UPDATE_TODO", todoId });
constshowTodoFilterAction = (filter = {}) => ({
type: "FILTER",
filter
});
export {
AddTodoAction,
DeleteTodoAction,
updateTodoAction,
showTodoFilterAction
};
reducer.js
consttodoReducer = (
state = []
, action
) => {
switch (action.type) {
case "ADD_TODO":
return [...state, action.todo];
case "REMOVE_TODO":
return state.filter(data => data.id !== action.todoId);
case "UPDATE_TODO":
return state.map(todo =>
todo.id === action.todoId
? { ...todo, isCompleted: !todo.isCompleted }
: todo
);
default:
return state;
}
};
consttodoFilterReducer = (state = {}, action) => {
switch (action.type) {
case "FILTER":
console.log("todoFilterReducer", state);
return Object.assign(
{}
, state
, {
filter: action.filter
}
);
default:
return state;
}
};
export { todoReducer, todoFilterReducer };
store.js
import { createStore
, combineReducers } from "redux";
import { todoReducer
, todoFilterReducer } from "./reducer";
import { loadState
, saveState } from "../localStorage";
import throttle from "lodash/throttle";
export default () => {
constpersistedState = loadState();
console.log("persistedState", persistedState);
const store = createStore(
combineReducers({
todos: todoReducer,
todoFilters: todoFilterReducer
}),
persistedState
);
store.subscribe(
throttle(() => {
saveState(store.getState());
}),
1000
);
return store;
};
todos.js
export default (todos, { filter }) => {
console.log(filter);
return todos.filter(todo => {
if (filter === "COMPLETED") {
return todo.isCompleted;
}
if (filter === "ACTIVE") {
return !todo.isCompleted;
}
return todo;
});
};
index.js
import React from "react";
import ReactDOM from "react-dom";
import createStore from "./components/store";
import Root from "./components/Root";
import "./styles.css";
const store = createStore();
constrootElement = document.getElementById("root");
ReactDOM.render(<Root store={store} />, rootElement);
localStorage.js
constloadState = () => {
try {
constserializedState = localStorage.getItem("state");
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
constsaveState = state => {
try {
constserializeState = JSON.stringify(state);
localStorage.setItem("state", serializeState);
} catch (err) {}
};
export { loadState, saveState };
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
}
Output:
When we scroll down in the Output window, below are the Output that will appear.
When you click the “Open in New Window” button notified by red arrow in the above image the following content will appear on the window:
When we click List dropdown, the whole appears as:
After adding each task through the orange box, you have to refresh the window so that every task appears in the green box. Where you can check box for completed tasks.
Advantages of UUID
Some of the advantages are given below:
- There are 5 different versions of UUID which can be used in React Native.
- It can run on node.js and all of the different browsers.
- We can generate strong cryptographically created Random numbers using crypto.randomBytes(n) in node.js.
- Using UUIDs can help in securing the information provided and also keeps an unique identifier for each of the information’s provided.
- The unique values help in easy access of the required data in the databases.
Conclusion
On the basis of the above article, we understood how Universal Unique Identifiers are useful for an application. We have explained the working of UUIDs and how the different versions vary in its generation and the example helps us to understand its usage in a real-world application.
Recommended Articles
This is a guide to React Native UUID. Here we also discuss the introduction, syntax, and working of react native uuid along with different examples and its code implementation. You may also have a look at the following articles to learn more –