Updated June 7, 2023
Introduction of React Native UUID
UUID stands for Universal Unique Identifier. It has a 128-bit number for uniquely identifying any object or entity. A Universal Unique Identifier depends on combining the different components, ensuring its uniqueness. Any UUID which is guaranteed contains three categories of elements. Firstly, it refers to the host’s address that 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 using the universally unique identifier to identify 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 combine three components as discussed above. The host computer’s address, the specific time and date of the UUID generation, and a combination of random characters or numbers ensure 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 increase the possibility of the UUID’s uniqueness.
1. Tasks List/ Notes list using
In the example below, we have imported uuid from 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, the Output will appear below.
While clicking the “Open in New Window” button, notified by the red arrow in the above image, the following content will appear on the window:
When we click the List dropdown, the whole appears as:
After adding each task through the orange box, you must refresh the window so every task appears in the green box. Where you can check the box for completed tasks.
Advantages of UUID
Some of the advantages are given below:
- Five different versions of UUID can be used in React Native.
- It can run on node.js and all of the other 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 a unique identifier for each of the information’s provided.
- The unique values help easily access the required data in the databases.
Conclusion
Based on the above article, we understood how Universal Unique Identifiers are helpful for an application. We have explained the working of UUIDs and how the different versions vary in their generation, and the example helps us to understand its usage in a real-world application.
Recommended Articles
We hope that this EDUCBA information on “React Native UUID” was beneficial to you. You can view EDUCBA’s recommended articles for more information.