Skip to content

Commit

Permalink
context added
Browse files Browse the repository at this point in the history
  • Loading branch information
Kacperacy committed Apr 3, 2024
1 parent 67c602e commit 4fa6ce4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 24 deletions.
26 changes: 20 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
import { useState } from "react";
import FilesContext from "./FilesContext";
import FileTab from "./components/TopBar";
import OpenedFile from "./types/OpenedFile";

function App() {
const files = [
{ name: "file1", filePath: "file1", active: true },
{ name: "file2", filePath: "file2", active: false },
{ name: "file3", filePath: "file3", active: false },
];
const [files, setFiles] = useState<OpenedFile[]>([
{
name: "index.html",
filePath: "index.html",
active: true,
},
{
name: "styles.css",
filePath: "styles.css",
active: false,
},
{
name: "script.js",
filePath: "script.js",
active: false,
},
]);

return (
<FilesContext.Provider value={files}>
<FilesContext.Provider value={{ files, setFiles }}>
<div className="w-screen h-screen bg-slate-600">
<FileTab />
</div>
Expand Down
26 changes: 9 additions & 17 deletions src/FilesContext.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import React, { createContext, useState, useContext } from "react";
import { createContext } from "react";
import OpenedFile from "./types/OpenedFile";

const FilesContext = createContext<OpenedFile[]>([]);
const FilesContext = createContext<{
files: OpenedFile[];
setFiles: React.Dispatch<React.SetStateAction<OpenedFile[]>>;
}>({
files: [],
setFiles: () => console.error("FilesContext not initialized"),
});

type FileProviderProps = {
children: React.ReactNode;
};

export const FileProvider = ({ children: FileProviderProps }) => {
const [files, setFiles] = useState<OpenedFile[]>([]);
return (
<FilesContext.Provider value={[files, setFiles]}>
{children}
</FilesContext.Provider>
);
};

// Custom hook to use the context
export const useFilesContext = () => useContext(FilesContext);
export default FilesContext;
2 changes: 1 addition & 1 deletion src/components/TopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import FileTab from "./files/FileTab";
import FilesContext from "../FilesContext";

function TopBar() {
const [files, setFiles] = useContext(FilesContext);
const { files, setFiles } = useContext(FilesContext);

function closeFile(event: React.MouseEvent, filePath: string) {
event.stopPropagation();
Expand Down

0 comments on commit 4fa6ce4

Please sign in to comment.