As you know a lot of developers replaced redux with react context feature. So I want to show you how I am using it in my products.
We will create a Todo list using context API (based on typescript).
I will use bootstrap for design._
_
Final view of our code.
Let's get started!
At first, we must create our context in thecontexts
folder.
TodoContext.ts
import{createContext}from"react";exportinterfaceITodo{name:string;completed:boolean;}interfaceITodoContext{data:ITodo[];updateData:Function;}exportconstTodoContext=createContext<ITodoContext>({data:[],updateData:(data:ITodo[])=>{thrownewError('updateData not implemented')}})
Here we can see that we are creating an interface for todo items, and also for todo context.
My context has two values, the first one is the data that it must contain and the second one is the function that will update the data.
After creating context we must create a provider for it.
We are creating it in theproviders
folder.
TodoProvider.tsx
import{FC,ReactNode,useState}from"react";import{ITodo,TodoContext}from"../contexts/TodoContext";interfaceITodoProvider{children:ReactNode}exportconstTodoProvider:FC<ITodoProvider>=({children})=>{const[data,setData]=useState<ITodo[]>([]);constupdateData=(data:ITodo[])=>{setData(data);}return(<TodoContext.Providervalue={{data,updateData}}>{children}</TodoContext.Provider>)}
In our todo provider, we will create and append the initial state for todo data. Also, we must create a function for handling data updates and appending it to our state.
Now we can start to use our created context API in our product.
What we must do:
- Render Todo List.
- Create Todo Item.
- Delete Todo Item.
So let's do it step by step
Render Todo List
Idea is to render the table with our todo data.
We will create aTodoList.tsx
file in thecomponents
folder.
exportconstTodoList=()=>{const{data:todoData}=useContext(TodoContext);return(<divclassName="container"><divclassName="d-flex justify-content-between"><divclassName="py-3"><h3>Todo List</h3></div></div><tableclassName="table table-striped table-dark"><thead><tr><td>Name</td><tdwidth="200">Status</td><tdwidth="150"align="right">Action</td></tr></thead><tbody>{todoData?.map((item:ITodo,index)=>(<trkey={`todo-${index}`}><td>{item.name}</td><td>{item.completed?<spanclassName="badge badge-info">Completed</span>:<spanclassName="badge badge-secondary">Not Completed</span>}</td></tr>))}</tbody></table></div>)}
Here you can see that we are using reactsuseContext
hook for getting our data from context.
const {data: todoData} = useContext(TodoContext);
So we will have always up-to-date data that we are getting fromTodoContext
.
Of course, it will be always empty, so we must add create functionality for it.
Lets create a simple form.
<formref={formRef}className="py-3 d-flex justify-content-between"onSubmit={handleCreate}><inputtype="text"name="name"className="form-control"/><buttontype="submit"className="btn btn-primary mx-1">Add</button></form>
We must createhandleCreate
function in our component for detecting submitting in form.
const{data:todoData,updateData:updateTodoData}=useContext(TodoContext);consthandleCreate=(event:React.SyntheticEvent)=>{event.preventDefault();const{target}=eventastypeofevent&{target:{name:{value:string};}}constname=target.name.value;updateTodoData([...todoData,{name:name,completed:false}])formRef?.current?.reset();}
Here you can see that we added updateData which we are taking from our context, and using it as updateTodoData for creating and saving new todo item.
Thats it. Now on submitting form it will create and render new item in our todo list.
By the same logic we can create delete functionality also.
consthandleDelete=(name:string)=>{constpayload=todoData.filter(item=>item.name!==name)updateTodoData(payload);}
We are taking the name and filtering our array by it.
After it, we are using ourupdateTodoData
function and update our array.
You can check the repositoryhere
And how you are using Context API in your applications?
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse