Skip to content

Instantly share code, notes, and snippets.

@jack2jm
Forked from Bhavya8181/Learn React
Last active March 18, 2024 05:41
Show Gist options
  • Save jack2jm/0389493a3f72558e41cfc5e5b21d6c57 to your computer and use it in GitHub Desktop.
Save jack2jm/0389493a3f72558e41cfc5e5b21d6c57 to your computer and use it in GitHub Desktop.
Full Doc to learn react
--------------------------------
https://docs.google.com/document/d/1xlMUk6OMMF42X3w1ZG94BnKcmbGI7f5FoF1kCyCBC9Q/edit?usp=sharing
Installations + SSL React
https://medium.com/@poudel.01anuj/deploying-reactjs-project-on-the-linux-server-with-ssl-certificate-https-aa14bf2737aa
--------------------------------
In react js you can store&use enviorment variable
- Create .env file in root of project
- Add variable with "REACT_APP" prefix (REACT_APP prefix must be required in every variable name)
- Use env variable using "process.env.varaible_name"
For Ex:
1. add variable in .env file
REACT_APP_API_ENDPOINT="http://20.169.229.247/saasoa_back/api"
2. Use variable in any page
const BASE_URL = process.env.REACT_APP_API_ENDPOINT;
-----
create build
basic
npm run build
with public url
npm run build PUBLIC_URL=https://jatin.com
Login Functionality
=====================
Ref Link:- https://dev.to/sanjayttg/jwt-authentication-in-react-with-react-router-1d03
Steps to impliment Login functionality in your page
1. create authProvider.js file inside src/provider and paste blow code into authProvide.js File
import axios from "axios";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
const AuthContext = createContext();
const AuthProvider = ({ children }) => {
// State to hold the authentication token
const [token, setToken_] = useState(localStorage.getItem("token"));
// Function to set the authentication token
const setToken = (newToken) => {
setToken_(newToken);
};
useEffect(() => {
if (token) {
axios.defaults.headers.common["Authorization"] = "Bearer " + token;
localStorage.setItem('token',token);
} else {
delete axios.defaults.headers.common["Authorization"];
localStorage.removeItem('token')
}
}, [token]);
// Memoized value of the authentication context
const contextValue = useMemo(
() => ({
token,
setToken,
}),
[token]
);
// Provide the authentication context to the children components
return (
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
);
};
export const useAuth = () => {
return useContext(AuthContext);
};
export default AuthProvider;
2. creating a ProtectedRoute.jsx Component for Authenticated Routes and Copy & Paste below code
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "provider/authProvider";
export const ProtectedRoute = ({children}) => {
const { token } = useAuth();
// Check if the user is authenticated
if (!token) {
// If not authenticated, redirect to the login page
return <Navigate to="/auth/login" />;
}
return children;
// If authenticated, render the child routes
// return <Outlet />;
};
3. Authenticated users routes wraped with yout ProtectedRoute component
For Ex: <Route path="/admin/index" element={<ProtectedRoute> <Component /> </ProtectedRoute>} />
4. The AuthProvider component is used to provide the authentication context to the application. It wraps around the Routes component
to make the authentication context available to all components within the Routes component tree.
For Ex: return (
<AuthProvider>
<Routes />
</AuthProvider>
);
5. Now implement Login and Logout
const handleLogin = () => {
//Login to call api for login and get token
//store token using setToken function
setToken(token);
navigate("/", { replace: true });
};
const handleLogout = () => {
setToken();
navigate("/", { replace: true });
};
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
handleSearchInput(signal);
//cleanup function
return () => {
controller.abort();
};
}, [searchInputValue]);
//create function to call search
const handleSearchInput = async (signal) => {
if (searchInputValue.length <= 2) {
return;
}
setIsLoading(true);
console.log("will search it -> ", searchInputValue);
setIsLoading(true);
const responseData = await searchQRList(props.type, signal);
if (responseData) {
//setTimeout(() => {
setQrCodeList(responseData);
//}, 1000);
}
setIsLoading(false);
};
api.js
-----
export const searchQRList = async (qr_type, signal) => {
try {
let token = localStorage.getItem("token");
let getUserUrl = `${BASE_URL}/qr-codes?type=` + qr_type;
let result = false;
const response = await api
.get(getUserUrl, {
headers: {
Authorization: `Bearer ${token}`,
},
signal: signal,
})
.then((response) => {
result = response.data.data;
})
.catch((error) => {
console.log(error);
if (error.response.data.relogin && error.response.data.relogin == 1) {
logoutUser();
return;
}
});
return result;
} catch (error) {
// let errorMessage = JSON.parse(error.request.responseText)
if (error.response) {
if (error.response.data.exception) {
return false;
}
return error.response.data;
}
//alertify.error(error.message);
console.error("Login error:", error.message);
return false;
}
};
1. Select default value auto-select
<SoftSelect
placeholder="Enter name to search"
options={stateList.map((state) => ({
value: state.id.toString(), // Assuming id is a string
label: state.name,
}))}
defaultValue={{ value: formData.state_id, label: formData.state_name }} //this should be required as object- not an ID
onChange={handleStateSelect}
menuPortalTarget={document.getElementById("create-edit-county-popup")}
menuPosition="fixed"
/>
#!/bin/sh
REACT_FOLDER_PATH="/var/www/html/cn_front_code"
PULL_ORIGIN_URL="REPO URL"
PROJECT_PUBLIC_URL="https://neuramonks.com"
PROJECT_BUILD_LIVE_FOLDER_NAME="cn_front_live"
PROJECT_BUILD_LIVE_FOLDER_PATH="/var/www/html/cn_front_live"
SERVER_BASE_PATH="/var/www/html"
echo "Folder path -> " . $REACT_FOLDER_PATH. "\n";
echo $REACT_FOLDER_PATH . "\n"
echo $PULL_ORIGIN_URL . "\n"
echo $PROJECT_PUBLIC_URL . "\n"
echo $PROJECT_BUILD_LIVE_FOLDER_NAME . "\n"
echo $PROJECT_BUILD_LIVE_FOLDER_PATH . "\n"
echo $SERVER_BASE_PATH . "\n"
#eg. cd /var/www/html/test-demo-code
cd $REACT_FOLDER_PATH
echo "pulling from -> " . $PULL_ORIGIN_UR. "\n"
git pull $PULL_ORIGIN_URL;
if [ $? -eq 0 ]; then
echo 'git pull success. "\n"'
else
echo 'git pull failure. "\n"'
exit 1;
fi
npm install;
echo "Creating build with PUBLIC URL -> " . $PROJECT_PUBLIC_URL. "\n";
PUBLIC_URL=$PROJECT_PUBLIC_URL npm run build;
cd $SERVER_BASE_PATH;
#delete folder if already exists
#eg. test-demo named folder deleted
echo "Deleting exist directory for project -> " . $PROJECT_BUILD_LIVE_FOLDER_NAME. "\n";
rm -r $PROJECT_BUILD_LIVE_FOLDER_NAME;
# create directory again fresh folder
#eg. test-demo named folder created
mkdir -p $PROJECT_BUILD_LIVE_FOLDER_NAME;
chmod -R 777 $PROJECT_BUILD_LIVE_FOLDER_PATH;
#navigate to that directory
# cd /var/www/html/test-demo-live
echo "Navigating to directory -> " . $PROJECT_BUILD_LIVE_FOLDER_PATH . "\n". "\n";
cd $PROJECT_BUILD_LIVE_FOLDER_PATH;
echo "Copy all new build files to current folder -> " . $PROJECT_BUILD_LIVE_FOLDER_PATH . "\n";
#copy build files to current frontend demo
#eg. cd /var/www/html/test-demo-code/build/* to test-demo-live
cp -r $REACT_FOLDER_PATH/build/* .
#Setting up htaccess file for react
#eg. cd /var/www/html/test-demo-code/.htaccessreact to test-demo-live/.htaccess
echo "Copy react project htaccess files -> " . $PROJECT_BUILD_LIVE_FOLDER_PATH. "\n";
cp $REACT_FOLDER_PATH/.htaccessreact .htaccess;
echo "******process is done**\n";
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment