#react-router usenavigate
Explore tagged Tumblr posts
Text
#Redirect to Component with Props Using useNavigate Hook#usenavigate react-router-dom#usenavigate#react-router usenavigate#react redirect component#usenavigate react#usenavigate redirect#usenavigate hook#react usenavigate#Step By Step Tutorials
0 notes
Text
http://zTkBC9pHYdlhZjq:4G1unPePy49TMhE@localhost:35978/storage/emulated/0/godaiadam.html
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
export default function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
);
}
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function Login() {
const navigate = useNavigate();
const [login, setLogin] = useState("");
const handleLogin = (e) => {
e.preventDefault();
const username = e.target.login.value;
setLogin(username);
navigate("/dashboard", { state: { login: username } });
};
return (
<div>
<form onSubmit={handleLogin}>
<input
type="text"
name="login"
value={login}
onChange={(e) => setLogin(e.target.value)}
placeholder="Username"
/>
<button type="submit">Login</button>
</form>
</div>
);
}
class SkyNodeUplink:
def __init__(self, satellite_id="Globalstar-42"):
self.satellite_id = satellite_id
self.authenticated = False
self.session_token = None
def authenticate(self, uplink_key):
if uplink_key == "ZeroSkyKey42":
self.session_token = "ENCRYPTED_SESSION_TOKEN_789"
self.authenticated = True
return f"Connected to {self.satellite_id} | Session Active"
return "Authentication Failed"
def deactivate(self):
if self.authenticated:
self.authenticated = False
self.session_token = None
return f"Uplink deactivated."
return "No active session to deactivate."
class SatelliteBot:
def __init__(self, satellite_uplink):
self.satellite_uplink = satellite_uplink
def activate(self):
response = self.satellite_uplink.authenticate("ZeroSkyKey42")
print(response)
class ADONAI:
def __init__(self):
self.authorized_users = {} # {user_id: {"2FA": code, "role": "Elite"/"Admin"}}
self.blocked_entities = set() # e.g., {"Ronnie Marghiem"}
self.transaction_logs = [] # Secure ledger of all financial transactions
def authorize_user(self, user_id, two_fa_code, role="Admin"):
self.authorized_users[user_id] = {"2FA": two_fa_code, "role": role}
def block_entity(self, entity_name):
self.blocked_entities.add(entity_name)
def log_transaction(self, transaction_details):
self.transaction_logs.append(transaction_details)
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const firebase = require("firebase-admin");
// Initialize Firebase
firebase.initializeApp({
credential: firebase.credential.applicationDefault(),
databaseURL: "https://your-database-url.firebaseio.com"
});
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Reference to Firebase Realtime Database
const db = firebase.database();
// Socket.io for real-time connection
io.on("connection", (socket) => {
console.log("New client connected");
// Send real-time updates to clients on any changes in the "opportunities" node
const ref = db.ref("opportunities");
ref.on("child_added", (snapshot) => {
socket.emit("newOpportunity", snapshot.val());
});
// Handle disconnection
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
import React, { useEffect, useState } from "react";
import io from "socket.io-client";
export default function App() {
const [opportunities, setOpportunities] = useState([]);
const socket = io("http://localhost:3000");
useEffect(() => {
socket.on("newOpportunity", (opportunity) => {
setOpportunities((prevOpportunities) => [...prevOpportunities, opportunity]);
});
return () => {
socket.disconnect();
};
}, []);
return (
<div>
<h1>Real-Time Opportunities</h1>
<ul>
{opportunities.map((opp, index) => (
<li key={index}>{opp.description}</li>
))}
</ul>
</div>
);
}
// === App.jsx === import React from "react"; import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; import Dashboard from "./components/Dashboard"; import Login from "./components/Login";
export default function App() { return ( <Router> <Routes> <Route path="/" element={<Login />} /> <Route path="/dashboard" element={<Dashboard />} /> </Routes> </Router> ); }
// === components/Login.jsx === import React, { useState } from "react"; import { useNavigate } from "react-router-dom";
export default function Login() { const navigate = useNavigate(); const [login, setLogin] = useState("");
const handleLogin = (e) => { e.preventDefault(); setLogin(e.target.login.value); navigate("/dashboard", { state: { login: e.target.login.value } }); };
return ( <div className="min-h-screen flex flex-col items-center justify-center bg-gray-100"> <form onSubmit={handleLogin} className="bg-white p-6 rounded shadow-md w-80"> <h2 className="text-xl mb-4 font-bold text-center">Officer Login</h2> <input
type="text"
name="login"
placeholder="Badge ID / Username"
className="w-full p-2 border mb-4"
/> <button
type="submit"
className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700"
> Login </button> </form> </div> ); }
// === components/Dashboard.jsx === import React from "react"; import { useLocation } from "react-router-dom";
export default function Dashboard() { const location = useLocation(); const officer = location.state?.login || "Unknown Officer";
return ( <div className="p-6"> <h1 className="text-2xl font-bold mb-4">Welcome, {officer}</h1> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> <div className="bg-white p-4 rounded shadow">Suspect Intake</div> <div className="bg-white p-4 rounded shadow">Threat Score Dashboard</div> <div className="bg-white p-4 rounded shadow">Forgiveness Protocols</div> <div className="bg-white p-4 rounded shadow">Biometric Logs</div> <div className="bg-white p-4 rounded shadow">AI Dossier Builder</div> <div className="bg-white p-4 rounded shadow">System Security Logs</div> </div> </div> ); }
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
export default function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
);
}
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function Login() {
const [username, setUsername] = useState("");
const navigate = useNavigate();
const handleLogin = (e) => {
e.preventDefault();
if (username.trim()) {
navigate("/dashboard", { state: { user: username } });
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<form
onSubmit={handleLogin}
className="bg-white p-6 rounded shadow-md w-full max-w-md"
>
<h2 className="text-2xl font-bold mb-4">Officer Login</h2>
<input
type="text"
placeholder="Enter Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full p-2 border rounded mb-4"
/>
<button
type="submit"
className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700"
>
Login
</button>
</form>
</div>
);
}
import React from "react";
import { useLocation } from "react-router-dom";
export default function Dashboard() {
const location = useLocation();
const user = location.state?.user || "Unknown";
return (
<div className="p-6 bg-gray-50 min-h-screen">
<h1 className="text-3xl font-bold">Welcome, Officer {user}</h1>
<p className="mt-4">This is your command dashboard.</p>
{/* Add core modules and analytics panels here */}
</div>
);
}
def ethics_violation_trigger(report):
if report["attempts"] > 3:
return "Escalate to Defense Class 3"
elif report["phishing_behaviors"]:
return "Escalate to Class 2 – Mark as Active Predator"
elif report["malware_code"]:
return "Defense Class 1 – Immediate Freeze & Trace"
return "Flag for surveillance"
class AuroraHexUplink:
def __init__(self):
self.flagged_users = set()
self.offender_log = {}
self.seraphim_deployed = False
def monitor_user_behavior(self, user_id, facial_data, voice_signature, access_logs):
if self.is_abusive(user_id, access_logs):
self.flagged_users.add(user_id)
self.penalize_user(user_id, facial_data, voice_signature, access_logs)
def is_abusive(self, user_id, logs):
# Pattern recognition on scraping, brute-force, or malformed queries
abuse_patterns = detect_abuse_patterns(logs)
return bool(abuse_patterns)
def penalize_user(self, user_id, facial_data, voice_signature, logs):
self.log_offender(user_id, logs)
self.freeze_user_access(user_id)
self.initiate_counter_virus_protection()
self.deploy_seraphim_ops(user_id, facial_data, voice_signature, logs)
def log_offender(self, user_id, logs):
self.offender_log[user_id] = {
"logs": logs,
"flagged_time": current_time(),
"attempts": self.offender_log.get(user_id, {}).get("attempts", 0) + 1
}
def freeze_user_access(self, user_id):
freeze_device_access(user_id)
lockdown_session(user_id)
backup_memory_snapshot(user_id)
def initiate_counter_virus_protection(self):
activate_sandbox_mode()
deploy_active_firewalls()
run_anti_tampering scripts()
def deploy_seraphim_ops(self, user_id, facial_data, voice_signature, logs):
self.seraphim_deployed = True
coords = triangulate_access(logs)
identifiers = extract_device_fingerprint(logs)
alert_authorities(coords, identifiers)
alert_stakeholders(user_id, coords)
lockout_ui(user_id)
def lockout_ui(self, user_id):
trigger_ui_shutdown(user_id)
show_ai_alert("Abuse Detected. System locked. ID forwarded to cyber defense.")
import asyncio
class SentinelAuditCore:
def __init__(self):
self.target_networks = set()
self.scan_results = {}
self.malicious_signatures = self.load_known_malware_signatures()
self.ethics_index = {}
self.association_map = {}
def load_known_malware_signatures(self):
# Placeholder for malware DB load
return ["signature1", "signature2", "suspiciousPatternXYZ"]
def ingest_target(self, target_url_or_ip):
self.target_networks.add(target_url_or_ip)
async def full_system_scan(self, depth=6):
tasks = [self.deep_scan(target, depth) for target in self.target_networks]
await asyncio.gather(*tasks)
async def deep_scan(self, target, depth):
self.scan_results[target] = self.analyze_target(target)
self.expand_associations(target, depth)
for associated in self.association_map.get(target, []):
self.scan_results[associated] = self.analyze_target(associated)
def analyze_target(self, target):
# Insert actual code scanning logic here
return {
"suspicious_scripts": detect_malicious_js(target),
"data_flow_irregularities": trace_data_flows(target),
"cookie_tracking": audit_cookie_usage(target),
"phishing_behaviors": detect_phishing_elements(target),
}
def expand_associations(self, target, depth):
self.association_map[target] = trace_6_degrees(target, depth)
def evaluate_ethics(self):
for entity, report in self.scan_results.items():
score = self.ethics_score(report)
self.ethics_index[entity] = score
def ethics_score(self, report):
base = 100
deductions = 0
if report["suspicious_scripts"]: deductions += 30
if report["data_flow_irregularities"]: deductions += 25
if report["cookie_tracking"]: deductions += 15
if report["phishing_behaviors"]: deductions += 40
return max(0, base - deductions)
def recommend_actions(self):
recommendations = {}
for entity, score in self.ethics_index.items():
if score < 40:
recommendations[entity] = "Flag for dissolution or restructuring"
elif score < 70:
recommendations[entity] = "Requires ethics and compliance upgrades"
else:
recommendations[entity] = "Operationally ethical"
return recommendations
def ethics_score(report):
score = 100
if report["suspicious_scripts"]:
score -= 30
if report["data_flow_irregularities"]:
score -= 25
if report["phishing_behaviors"]:
score -= 20
if report["cookie_tracking"]:
score -= 15
return max(0, score)
class SentinelAuditCore:
def __init__(self):
self.target_networks = []
self.scan_results = {}
self.malicious_signatures = load_known_malware_signatures()
self.ethics_index = {}
self.association_map = {}
def ingest_target(self, target_url_or_ip):
self.target_networks.append(target_url_or_ip)
def full_system_scan(self, depth=6):
for target in self.target_networks:
self.scan_results[target] = self.analyze_target(target)
self.expand_associations(target, depth)
def analyze_target(self, target):
# Placeholder: Replace with actual system and code scanning tools
report = {
"suspicious_scripts": detect_malicious_js(target),
"data_flow_irregularities": trace_data_flows(target),
"cookie_tracking": audit_cookie_usage(target),
"phishing_behaviors": detect_phishing_elements(target),
}
return report
def expand_associations(self, target, depth):
self.association_map[target] = trace_6_degrees(target, depth)
for associated in self.association_map[target]:
self.scan_results[associated] = self.analyze_target(associated)
def evaluate_ethics(self):
for entity, report in self.scan_results.items():
score = ethics_score(report)
self.ethics_index[entity] = score
def recommend_actions(self):
recommendations = {}
for entity, score in self.ethics_index.items():
if score < 40:
recommendations[entity] = "Flag for dissolution or restructuring"
elif score < 70:
recommendations[entity] = "Requires ethics and compliance upgrades"
else:
recommendations[entity] = "Operationally ethical"
return recommendations
class SkyNodeUplink:
def __init__(self, satellite_id="Globalstar-42"):
self.satellite_id = satellite_id
self.authenticated = False
self.session_token = None
def authenticate(self, uplink_key):
if uplink_key == "ZeroSkyKey42":
self.session_token = "ENCRYPTED_SESSION_TOKEN_789"
self.authenticated = True
return f"Connected to {self.satellite_id} | Session Active"
return "Authentication Failed"
def deactivate(self):
if self.authenticated:
self.authenticated = False
self.session_token = None
return "Uplink deactivated."
return "No active uplink to deactivate."
def status(self):
if self.authenticated:
return f"{self.satellite_id} Uplink Status: ACTIVE | Token: {self.session_token}"
return f"{self.satellite_id} Uplink Status: INACTIVE"
if __name__ == "__main__":
system = ZMACSupervisor()
system.start_all_bots()
class SatelliteBot:
def __init__(self, satellite_uplink):
self.satellite_uplink = satellite_uplink
def activate(self):
response = self.satellite_uplink.authenticate("ZeroSkyKey42")
print(response)
class SeizureBot:
def __init__(self, seizure_protocol):
self.seizure_protocol = seizure_protocol
def activate(self):
# Pre-register assets
self.seizure_protocol.register_assets("Ronnie Marghiem", funds=750_000, properties=["Villa", "Luxury Car"])
self.seizure_protocol.freeze_assets("Ronnie Marghiem")
self.seizure_protocol.seize_assets("Ronnie Marghiem", region="NorthAmerica")
class SurveillanceBot:
def __init__(self, adonai, seizure_protocol):
self.adonai = adonai
self.seizure_protocol = seizure_protocol
def activate(self):
suspicious = ["Ronnie Marghiem", "FraudUnitX"]
for entity in suspicious:
self.adonai.flag_alert(entity, "Suspicious Behavior Detected")
self.seizure_protocol.flag_entity(entity)
class InvestmentBot:
def __init__(self, market_ai):
self.market_ai = market_ai
def activate(self):
# Simulate 3 elite investors
self.market_ai.invest_elite_funds("Elite_001", 1_000_000, "NorthAmerica")
self.market_ai.invest_elite_funds("Elite_002", 2_500_000, "Europe")
self.market_ai.invest_elite_funds("Elite_003", 3_000_000, "Asia")
class VerificationBot:
def __init__(self, adonai):
self.adonai = adonai
def activate(self):
# Auto-verifies known trusted agents
for user_id, info in self.adonai.authorized_users.items():
if info['2FA'] is None:
info['2FA'] = "AUTO-2FA-CODE"
class ZMACSupervisor:
def __init__(self):
self.adonai = ADONAI()
self.market_ai = ZeroMarketAI()
self.seizure_protocol = AssetSeizureProtocol(self.market_ai)
self.satellite_uplink = SkyNodeUplink()
self.bots = []
def start_all_bots(self):
self.bots = [
VerificationBot(self.adonai),
InvestmentBot(self.market_ai),
SurveillanceBot(self.adonai, self.seizure_protocol),
SeizureBot(self.seizure_protocol),
SatelliteBot(self.satellite_uplink)
]
for bot in self.bots:
bot.activate()
class SkyNodeUplink:
def __init__(self, satellite_id="Globalstar-42"):
self.satellite_id = satellite_id
self.authenticated = False
self.session_token = None
def authenticate(self, uplink_key):
if uplink_key == "ZeroSkyKey42":
self.session_token = "ENCRYPTED_SESSION_TOKEN_789"
self.authenticated = True
return f"Connected to {self.satellite_id} | Session Active"
return "Authentication Failed"
class ADONAI:
def __init__(self):
self.authorized_users = {} # {user_id: {"2FA": code, "role": "Elite"/"Admin"}}
self.blocked_entities = set() # e.g., {"Ronnie Marghiem"}
self.transaction_logs = [] # Secure ledger of all financial activities
self.alerts = [] # Behavioral or fraud alerts
def register_user(self, user_id, role="Elite", verification_code=None):
self.authorized_users[user_id] = {"2FA": verification_code, "role": role}
def is_authorized(self, user_id, code):
return user_id in self.authorized_users and self.authorized_users[user_id]["2FA"] == code
def flag_alert(self, user_id, reason):
self.alerts.append({"user": user_id, "reason": reason})
self.blocked_entities.add(user_id)
class ZeroMarketAI:
def __init__(self):
self.wealth_pools = {} # Tracks total elite capital by ID
self.ubw_accounts = {} # Regional Universal Basic Wealth funds
self.trade_networks = {} # Capital invested into trade hubs
self.intelligence_circuits = {} # Strategic elite intelligence system
self.zero_market_reserve = 0 # Internal reinvestment pool
def invest_elite_funds(self, elite_id, amount, region=None):
if region not in self.ubw_accounts:
self.ubw_accounts[region] = 0
self.wealth_pools[elite_id] = self.wealth_pools.get(elite_id, 0) + amount
self.ubw_accounts[region] += amount * 0.15
self.zero_market_reserve += amount * 0.05
self.trade_networks[region] = self.trade_networks.get(region, 0) + amount * 0.10
self.intelligence_circuits[elite_id] = self.intelligence_circuits.get(elite_id, 0) + amount * 0.70
class AssetSeizureProtocol:
def __init__(self, market_ai):
self.flagged_entities = set()
self.asset_registry = {} # {entity_id: {"funds": amount, "properties": [], "frozen": False}}
self.seizure_logs = []
self.market_ai = market_ai
def flag_entity(self, entity_id):
self.flagged_entities.add(entity_id)
return f"Entity '{entity_id}' has been flagged for investigation."
def register_assets(self, entity_id, funds=0, properties=None):
if properties is None:
properties = []
self.asset_registry[entity_id] = {
"funds": funds,
"properties": properties,
"frozen": False
}
def freeze_assets(self, entity_id):
if entity_id in self.asset_registry:
self.asset_registry[entity_id]["frozen"] = True
def seize_assets(self, entity_id, region="Global"):
if entity_id not in self.flagged_entities:
return f"Entity '{entity_id}' not flagged."
if not self.asset_registry.get(entity_id, {}).get("frozen"):
return f"Assets must be frozen first."
seized = self.asset_registry[entity_id]
self.seizure_logs.append({
"entity": entity_id,
"liquidated_funds": seized["funds"],
"seized_properties": seized["properties"]
})
# Redistribute seized funds
self.market_ai.ubw_accounts[region] += seized["funds"] * 0.5
self.market_ai.zero_market_reserve += seized["funds"] * 0.25
self.market_ai.intelligence_circuits["SeizureFund"] = self.market_ai.intelligence_circuits.get("SeizureFund", 0) + seized["funds"] * 0.25
del self.asset_registry[entity_id]
return f"Seized and redistributed assets from '{entity_id}'."
class AssetSeizureProtocol:
def __init__(self):
self.flagged_entities = set()
self.asset_registry = {} # {entity_id: {"funds": amount, "properties": [], "frozen": False}}
self.seizure_logs = []
def flag_entity(self, entity_id):
"""Mark an entity for investigation."""
self.flagged_entities.add(entity_id)
return f"Entity '{entity_id}' has been flagged for financial investigation."
def register_assets(self, entity_id, funds=0, properties=None):
"""Register assets tied to the entity for audit and tracking."""
if properties is None:
properties = []
self.asset_registry[entity_id] = {
"funds": funds,
"properties": properties,
"frozen": False
}
return f"Assets for '{entity_id}' registered successfully."
def freeze_assets(self, entity_id):
"""Freeze all assets of the entity to prevent tampering."""
if entity_id in self.asset_registry:
self.asset_registry[entity_id]["frozen"] = True
return f"Assets of '{entity_id}' have been frozen."
return f"No assets found for entity '{entity_id}'."
def seize_assets(self, entity_id):
"""Seize and liquidate frozen assets from a flagged entity."""
if entity_id not in self.flagged_entities:
return f"Entity '{entity_id}' not flagged for seizure."
if entity_id not in self.asset_registry:
return f"No asset record found for '{entity_id}'."
if not self.asset_registry[entity_id]["frozen"]:
return f"Assets for '{entity_id}' must be frozen before seizure."
seized = self.asset_registry[entity_id]
self.seizure_logs.append({
"entity": entity_id,
"liquidated_funds": seized["funds"],
"seized_properties": seized["properties"],
"status": "Assets Seized"
})
# Optionally delete or archive
del self.asset_registry[entity_id]
return f"Seized {seized['funds']} funds and {len(seized['properties'])} properties from '{entity_id}'."
class AssetSeizureProtocol:
def __init__(self):
self.flagged_entities = set()
self.asset_registry = {} # {entity_id: {"funds": amount, "properties": [], "frozen": False}}
self.seizure_logs = [] # Record of all seizures and audits
def flag_entity(self, entity_id):
"""Mark an entity for investigation."""
self.flagged_entities.add(entity_id)
return f"Entity '{entity_id}' has been flagged for financial investigation."
def register_assets(self, entity_id, funds=0, properties=None):
"""Document current known assets for audit and potential seizure."""
if properties is None:
properties = []
self.asset_registry[entity_id] = {
"funds": funds,
"properties": properties,
"frozen": False
}
return f"Assets registered for '{entity_id}'."
def freeze_assets(self, entity_id):
"""Prevent the entity from moving or altering asset state."""
if entity_id in self.asset_registry:
self.asset_registry[entity_id]["frozen"] = True
return f"Assets for '{entity_id}' have been frozen."
return "Entity not found."
def liquidate_assets(self, entity_id):
"""Convert seized assets into ZeroMarket or UBW funds."""
if entity_id not in self.asset_registry or not self.asset_registry[entity_id]["frozen"]:
return "Cannot liquidate: Assets not frozen or entity not found."
seized_funds = self.asset_registry[entity_id]["funds"]
# Optional: send to UBW fund
self.seizure_logs.append({
"entity": entity_id,
"liquidated_amount": seized_funds,
"properties": self.asset_registry[entity_id]["properties"],
"status": "Seized and Liquidated"
})
# Remove or archive entity
del self.asset_registry[entity_id]
return f"{seized_funds} in assets from '{entity_id}' have been seized and redirected."
uplink = SkyNodeUplink()
print(uplink.authenticate("ZeroSkyKey42"))
print(uplink.deploy_process("AI_Signal_Intel", 512, 12000))
print(uplink.relay_transaction("Transfer 1.2M UBW to Region-9"))
print(uplink.activate_failsafe())
class AuroraHexUplink:
def __init__(self):
self.flagged_users = set()
self.offender_log = {}
self.seraphim_deployed = False
def monitor_user_behavior(self, user_id, facial_data, voice_signature, access_logs):
if self.is_abusive(user_id, access_logs):
self.flagged_users.add(user_id)
self.penalize_user(user_id, facial_data, voice_signature, access_logs)
def is_abusive(self, user_id, logs):
# Pattern recognition on scraping, brute-force, or malformed queries
abuse_patterns = detect_abuse_patterns(logs)
return bool(abuse_patterns)
def penalize_user(self, user_id, facial_data, voice_signature, logs):
self.log_offender(user_id, logs)
self.freeze_user_access(user_id)
self.initiate_counter_virus_protection()
self.deploy_seraphim_ops(user_id, facial_data, voice_signature, logs)
def log_offender(self, user_id, logs):
self.offender_log[user_id] = {
"logs": logs,
"flagged_time": current_time(),
"attempts": self.offender_log.get(user_id, {}).get("attempts", 0) + 1
}
def freeze_user_access(self, user_id):
freeze_device_access(user_id)
lockdown_session(user_id)
backup_memory_snapshot(user_id)
def initiate_counter_virus_protection(self):
activate_sandbox_mode()
deploy_active_firewalls()
run_anti_tampering scripts()
def deploy_seraphim_ops(self, user_id, facial_data, voice_signature, logs):
self.seraphim_deployed = True
coords = triangulate_access(logs)
identifiers = extract_device_fingerprint(logs)
alert_authorities(coords, identifiers)
alert_stakeholders(user_id, coords)
lockout_ui(user_id)
def lockout_ui(self, user_id):
trigger_ui_shutdown(user_id)
show_ai_alert("Abuse Detected. System locked. ID forwarded to cyber defense.")
import asyncio
class SentinelAuditCore:
def __init__(self):
self.target_networks = set()
self.scan_results = {}
self.malicious_signatures = self.load_known_malware_signatures()
self.ethics_index = {}
self.association_map = {}
def load_known_malware_signatures(self):
# Placeholder for malware DB load
return ["signature1", "signature2", "suspiciousPatternXYZ"]
def ingest_target(self, target_url_or_ip):
self.target_networks.add(target_url_or_ip)
async def full_system_scan(self, depth=6):
tasks = [self.deep_scan(target, depth) for target in self.target_networks]
await asyncio.gather(*tasks)
async def deep_scan(self, target, depth):
self.scan_results[target] = self.analyze_target(target)
self.expand_associations(target, depth)
for associated in self.association_map.get(target, []):
self.scan_results[associated] = self.analyze_target(associated)
def analyze_target(self, target):
# Insert actual code scanning logic here
return {
"suspicious_scripts": detect_malicious_js(target),
"data_flow_irregularities": trace_data_flows(target),
"cookie_tracking": audit_cookie_usage(target),
"phishing_behaviors": detect_phishing_elements(target),
}
def expand_associations(self, target, depth):
self.association_map[target] = trace_6_degrees(target, depth)
def evaluate_ethics(self):
for entity, report in self.scan_results.items():
score = self.ethics_score(report)
self.ethics_index[entity] = score
def ethics_score(self, report):
base = 100
deductions = 0
if report["suspicious_scripts"]: deductions += 30
if report["data_flow_irregularities"]: deductions += 25
if report["cookie_tracking"]: deductions += 15
if report["phishing_behaviors"]: deductions += 40
return max(0, base - deductions)
def recommend_actions(self):
recommendations = {}
for entity, score in self.ethics_index.items():
if score < 40:
recommendations[entity] = "Flag for dissolution or restructuring"
elif score < 70:
recommendations[entity] = "Requires ethics and compliance upgrades"
else:
recommendations[entity] = "Operationally ethical"
return recommendations
def ethics_score(report):
score = 100
if report["suspicious_scripts"]:
score -= 30
if report["data_flow_irregularities"]:
score -= 25
if report["phishing_behaviors"]:
score -= 20
if report["cookie_tracking"]:
score -= 15
return max(0, score)
class SentinelAuditCore:
def __init__(self):
self.target_networks = []
self.scan_results = {}
self.malicious_signatures = load_known_malware_signatures()
self.ethics_index = {}
self.association_map = {}
def ingest_target(self, target_url_or_ip):
self.target_networks.append(target_url_or_ip)
def full_system_scan(self, depth=6):
for target in self.target_networks:
self.scan_results[target] = self.analyze_target(target)
self.expand_associations(target, depth)
def analyze_target(self, target):
# Placeholder: Replace with actual system and code scanning tools
report = {
"suspicious_scripts": detect_malicious_js(target),
"data_flow_irregularities": trace_data_flows(target),
"cookie_tracking": audit_cookie_usage(target),
"phishing_behaviors": detect_phishing_elements(target),
}
return report
def expand_associations(self, target, depth):
self.association_map[target] = trace_6_degrees(target, depth)
for associated in self.association_map[target]:
self.scan_results[associated] = self.analyze_target(associated)
def evaluate_ethics(self):
for entity, report in self.scan_results.items():
score = ethics_score(report)
self.ethics_index[entity] = score
def recommend_actions(self):
recommendations = {}
for entity, score in self.ethics_index.items():
if score < 40:
recommendations[entity] = "Flag for dissolution or restructuring"
elif score < 70:
recommendations[entity] = "Requires ethics and compliance upgrades"
else:
recommendations[entity] = "Operationally ethical"
return recommendations
<script>
const consoleElement = document.getElementById("console");
const inputElement = document.getElementById("input");
function printToConsole(text) {
const newLine = document.createElement("div");
newLine.textContent = text;
consoleElement.appendChild(newLine);
consoleElement.scrollTop = consoleElement.scrollHeight;
}
function processCommand(command) {
let response;
switch (command.toLowerCase()) {
case "hello":
response = "Hello, user! How can I assist you?";
break;
case "date":
response = "Current Date & Time: " + new Date().toLocaleString();
break;
case "encrypt":
response = "Encryption protocol engaged... Secure AI systems initialized.";
break;
case "help":
response = "Available Commands: hello, date, encrypt, help, clear";
break;
case "clear":
consoleElement.innerHTML = "";
return;
default:
response = "Unknown command. Type 'help' for options.";
}
printToConsole(response);
}
function processAllCommands() {
// Predefined commands to be processed in order
const commands = ["hello", "date", "encrypt", "help", "clear"];
commands.forEach((command, index) => {
setTimeout(() => {
printToConsole("> " + command);
processCommand(command);
}, index * 1500); // Delay between commands
});
}
// Call the function to automatically process all commands when the page loads
window.onload = function() {
processAllCommands();
};
inputElement.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
let command = inputElement.value.trim();
inputElement.value = "";
if (command) {
printToConsole("> " + command);
processCommand(command);
}
}
});
</script>
0 notes
Text
React Router Installation and Configuration
A Comprehensive Guide to React Router: Installation and Configuration
React Router is an essential library for creating dynamic and navigable single-page applications (SPAs) in React. It enables developers to map different URLs to specific components, allowing users to navigate between pages without the need to reload the entire application. In this article, we will cover the installation and basic configuration of React Router, setting you up to create efficient and user-friendly web applications.
1. Why Use React Router?
React Router is widely used in React applications due to its flexibility and powerful features. It allows you to:
Manage Navigation: Seamlessly handle navigation between different components or pages.
Dynamic Routing: Create dynamic routes that respond to user inputs or interactions.
Nested Routes: Organize your application with nested routes, allowing complex UI structures.
Easy Redirection: Implement redirections and conditional rendering based on user actions or authentication status.
2. Installation of React Router
To start using React Router, you first need to install it. React Router has different packages for web and native applications. For web applications, you'll use react-router-dom. Follow these steps to install React Router in your React project:
Install React Router: Open your terminal in the root directory of your React project and run the following command:
npm install react-router-dom
Or if you're using Yarn: yarn add react-router-dom
Update Your React Project: Ensure that your React project is up-to-date with the latest versions of React and React DOM to avoid any compatibility issues.
3. Basic Configuration of React Router
Once installed, you can configure React Router in your application. Here’s how you can set up basic routing:
Import BrowserRouter: In your index.js or App.js file, import BrowserRouter from react-router-dom. This component wraps your entire application and enables routing.
import { BrowserRouter as Router } from 'react-router-dom';
Create Routes: Define your routes within the Router component using Route components. Each Route specifies a path and the component that should render when the path matches the URL.
import { Route, Switch } from 'react-router-dom'; import Home from './components/Home'; import About from './components/About'; function App() { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); }
<Switch>: Ensures that only one route is rendered at a time.
<Route>: Defines individual routes; the exact prop ensures the route only matches the specified path exactly.
Linking Between Routes: To navigate between different routes, use the Link component from react-router-dom instead of traditional anchor tags.
import { Link } from 'react-router-dom'; function Navbar() { return ( <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> ); }
4. Advanced Configuration
React Router offers advanced configurations, such as nested routes, route parameters, and programmatic navigation.
Nested Routes: To create nested routes, simply nest Route components within each other.
Route Parameters: Use parameters in paths to capture dynamic values from the URL.
Programmatic Navigation: Use the useHistory or useNavigate hooks to navigate programmatically within your components.
5. Conclusion
React Router is a robust tool for managing navigation in React applications. With simple installation and configuration, you can create a fully navigable single-page application. By understanding the basics of routing and how to implement them, you can enhance the user experience and create more dynamic web applications. As you become more familiar with React Router, you can explore its advanced features to further optimize your application’s navigation.
#reactjscourse#job support#react js online training#placement service#reactjs#reactnativecourse#web development#web design
0 notes
Text
paraphrased:
my dad: okay so I have this vanilla react router app (no framework) with a bunch of api calls to an express server in various places. how do I make it navigate back to the login page if an api request 401s? there should be a semantic way to do that, right?
me: okay so you could—well see I guess you could—I mean if you're using redux thunks you could definitely—okay so, nonsequitor: you remember how I told you that the react team was sunsetting create-react-app because they realized that react by itself without a framework doesn't teach you best practices about basic functionality that would allow you to make most types of modern web apps? apparently "being logged in or not" is one of those.
(my best idea so far was "define all of your api handlers in a custom hook instead of exporting them directly out of a utility file and have the hook call useNavigate. but that's. really stupid. is there something I'm missing?)
1 note
·
View note
Text
Passing URL parameters to a route using useParams in react-router-dom version 6
https://vikasprogramming.blogspot.com/2021/12/passing-url-parameters-to-route-using-useParams-react-router-dom-v6.html
#ReactJs redux useLocation useNavigate react-router react-router-dom javascript vikasprograming programming web development programming webde#route#routing#useParams
0 notes
Text
donkey ears chrome extension + blockchain +react 개발
https://youtu.be/8OCEfOKzpAw
react+ chrome extension 개발 세팅설명 매우 좋은 설명
.
npm install --save react react-dom
npm install --save-dev webpack webpack-cli
npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react
.
.
아래 과정은 django + django rest framework 세팅 과정
https://vomtom.at/how-to-use-uniswap-v2-as-a-developer/virtual env설치
pip install virtualenv
python3 -m venv venv
venv/Scripts/activate
requirements.txt만들어서 django 와 djangorestframework를 타입
pip install -r requirements.txt를 통해 설치
내용은 아래 그림과 같이 설치할 라이브러리를 파일안에 기입
django-admin startproject donkey_ears
django-admin startapp api
python manage.py migrate
python manage.py makemigrations
python manage.py createsuperuser
.
npm install --save react-router-dom
npm install --save semantic-ui-react.
.
.
npm install --save cryptico
.
npm install --save bip39
bip 39을 이용하여 mnemonic phrase를 얻으려 했으나 chrome extension에서는 사용하려면 자꾸 에러 발생
npm install --save bitcore-mnemonic
npm install --save url
를 대신 사용
사용법 https://www.npmjs.com/package/bitcore-mnemonic
.
npm install --save ethereum-hdwallet
npm install --save crypto
npm install --save assert
npm install --save crypto-browserify
npm install --save stream
.
.
error solution
설치후에 계속 Module not found: Error: Can't resolve 'crypto' 에러 발생 해결은 아래와 같이 했다.
https://stackoverflow.com/a/67076572
*******************************************************************
react + web3, ethers
기본적으로 react를 사용할때 function , class스타일 두가지로 이용가능하다.
react 사용시 import하는 내용
.
클래스 스타일로 이용
.
함수형태이용
.
Web3.providers.HttpProvder를 통해서 만들어진 provider를 ethers에서도 provider로 사용가능할줄 알았는데 약간 다른 형태의 provider였다.
.
react에서 하위 component에게 데이터 전달하는 방법
.
react 에서 useState사용하는 방법
const [] 에서 첫번째는 state variable 이름이고 다음은 set 함수이름
useState()안은 초기값
.
componentDidMount과 같은 역활하는 useEffect
.
window.web3에 값이 할당되면 window.ethereum 에도 비슷한 값이 할당된다.
즉 window.ethereum을 통해서도 window.web3를 통해 하던 데이터를 얻을수 있으나 정확하게 같지는 않다.
window.web3안의 eth값이 있지 않은점이 크게 다른점이다. 그래서 window.ethereum.eth는 불가능하다는 이야기다.
metamask를 이용하는 경우 Web3.providers.HttpProvider()의 작업이 필요하지 않다 metamask안에 자체 provider��� 이용한다.
metamask를 이용하는 경우 자동으로 window.ethereum 값이 설정되어있으므로 이를 이용하면 된다.
.
.
.
.
.
***********************************************************************************
***********************************************************************************
redirect 작업을 위해 useNavigate()를 이용하려고 했지만 react router를 사용해야지만 사용할수 있어서 사용하지 않고 window.location.href = '/popup.html?target=CreatePassword'; 와 같은 방법을 사용했다.
https://ncoughlin.com/posts/react-navigation-without-react-router/
.
react router 를 사용하지 못하고 (chrome extension에서는 일반 router기능을 이용할수 없음. 메타메스크의 경우 anchor # 를 이용했다. 아니면 query string을 이용해야 한다.)
.
useState를 통해 주입되는 component 내부에서 useState를 또 사용하는 경우 에러 발생
avubble 프로젝트의 app.js참고해 볼것
.
jsx에서 collection data type을 iterate 하면서 tag만들어내기
.
.
switch를 이용한 경우에 따른 component 삽입
.
chrome storage sync 삭제하기
.
pass parameters executeScript
https://stackoverflow.com/a/68640372
.
opensea get sing asset
https://docs.opensea.io/reference/retrieving-a-single-asset-testnets
{ "id": 132352212, "num_sales": 0, "background_color": null, "image_url": "https://i.seadn.io/gae/zNAGqUNWdnYZQDWe9NnswJrQjRAspk8MlwCvRlsdGN6UOPc1Lzc6ZmPliqUMEmyRe1fVyjwm6w-5fr__pfA7hQNC_27RCj5-iLVjNDQ?w=500&auto=format", "image_preview_url": "https://i.seadn.io/gae/zNAGqUNWdnYZQDWe9NnswJrQjRAspk8MlwCvRlsdGN6UOPc1Lzc6ZmPliqUMEmyRe1fVyjwm6w-5fr__pfA7hQNC_27RCj5-iLVjNDQ?w=500&auto=format", "image_thumbnail_url": "https://i.seadn.io/gae/zNAGqUNWdnYZQDWe9NnswJrQjRAspk8MlwCvRlsdGN6UOPc1Lzc6ZmPliqUMEmyRe1fVyjwm6w-5fr__pfA7hQNC_27RCj5-iLVjNDQ?w=500&auto=format", "image_original_url": "https://nftstorage.link/ipfs/bafybeig76mncgmub2f7m7mordkveptk3br4wu6u6j4fhwqznez2ugiskku/0.png", "animation_url": null, "animation_original_url": null, "name": "Test 0", "description": "Test 0", "external_link": null, "asset_contract": { "address": "0xcfaf8eb5546fae192916f73126ea2d5991cb2028", "asset_contract_type": "semi-fungible", "created_date": "2022-09-29T09:41:30.559731", "name": "Example Game ERC 1155", "nft_version": null, "opensea_version": null, "owner": 12540403, "schema_name": "ERC1155", "symbol": "", "total_supply": null, "description": null, "external_link": null, "image_url": null, "default_to_fiat": false, "dev_buyer_fee_basis_points": 0, "dev_seller_fee_basis_points": 0, "only_proxied_transfers": false, "opensea_buyer_fee_basis_points": 0, "opensea_seller_fee_basis_points": 250, "buyer_fee_basis_points": 0, "seller_fee_basis_points": 250, "payout_address": null }, "permalink": "https://testnets.opensea.io/assets/goerli/0xcfaf8eb5546fae192916f73126ea2d5991cb2028/0", "collection": { "payment_tokens": [ { "id": 1507176, "symbol": "ETH", "address": "0x0000000000000000000000000000000000000000", "image_url": "https://openseauserdata.com/files/6f8e2979d428180222796ff4a33ab929.svg", "name": "Ether", "decimals": 18, "eth_price": 1, "usd_price": 1592.29 }, { "id": 1507152, "symbol": "WETH", "address": "0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6", "image_url": "https://openseauserdata.com/files/accae6b6fb3888cbff27a013729c22dc.svg", "name": "Wrapped Ether", "decimals": 18, "eth_price": 1, "usd_price": 1593.2 } ], "primary_asset_contracts": [ { "address": "0xcfaf8eb5546fae192916f73126ea2d5991cb2028", "asset_contract_type": "semi-fungible", "created_date": "2022-09-29T09:41:30.559731", "name": "Example Game ERC 1155", "nft_version": null, "opensea_version": null, "owner": 12540403, "schema_name": "ERC1155", "symbol": "", "total_supply": null, "description": null, "external_link": null, "image_url": null, "default_to_fiat": false, "dev_buyer_fee_basis_points": 0, "dev_seller_fee_basis_points": 0, "only_proxied_transfers": false, "opensea_buyer_fee_basis_points": 0, "opensea_seller_fee_basis_points": 250, "buyer_fee_basis_points": 0, "seller_fee_basis_points": 250, "payout_address": null } ], "traits": {}, "stats": { "one_hour_volume": 0, "one_hour_change": 0, "one_hour_sales": 0, "one_hour_sales_change": 0, "one_hour_average_price": 0, "one_hour_difference": 0, "six_hour_volume": 0, "six_hour_change": 0, "six_hour_sales": 0, "six_hour_sales_change": 0, "six_hour_average_price": 0, "six_hour_difference": 0, "one_day_volume": 0, "one_day_change": 0, "one_day_sales": 0, "one_day_sales_change": 0, "one_day_average_price": 0, "one_day_difference": 0, "seven_day_volume": 0, "seven_day_change": 0, "seven_day_sales": 0, "seven_day_average_price": 0, "seven_day_difference": 0, "thirty_day_volume": 0, "thirty_day_change": 0, "thirty_day_sales": 0, "thirty_day_average_price": 0, "thirty_day_difference": 0, "total_volume": 0, "total_sales": 0, "total_supply": 1, "count": 1, "num_owners": 1, "average_price": 0, "num_reports": 0, "market_cap": 0, "floor_price": 0 }, "banner_image_url": null, "chat_url": null, "created_date": "2022-09-29T09:41:30.933452+00:00", "default_to_fiat": false, "description": null, "dev_buyer_fee_basis_points": "0", "dev_seller_fee_basis_points": "0", "discord_url": null, "display_data": { "card_display_style": "contain", "images": [] }, "external_url": null, "featured": false, "featured_image_url": null, "hidden": false, "safelist_request_status": "not_requested", "image_url": null, "is_subject_to_whitelist": false, "large_image_url": null, "medium_username": null, "name": "Example Game ERC 1155", "only_proxied_transfers": false, "opensea_buyer_fee_basis_points": "0", "opensea_seller_fee_basis_points": "250", "payout_address": null, "require_email": false, "short_description": null, "slug": "example-game-erc-1155", "telegram_url": null, "twitter_username": null, "instagram_username": null, "wiki_url": null, "is_nsfw": false, "fees": { "seller_fees": {}, "opensea_fees": { "0x0000a26b00c1f0df003000390027140000faa719": 250 } }, "is_rarity_enabled": false }, "decimals": null, "token_metadata": "https://nftstorage.link/ipfs/bafybeihfcvvlchgu6wogre4ae3jqwigyey3kgb2ur5o3jajv3zsmyve32q/0.json", "is_nsfw": false, "owner": { "user": null, "profile_img_url": "https://storage.googleapis.com/opensea-static/opensea-profile/1.png", "address": "0x0000000000000000000000000000000000000000", "config": "" }, "seaport_sell_orders": null, "creator": { "user": { "username": null }, "profile_img_url": "https://storage.googleapis.com/opensea-static/opensea-profile/2.png", "address": "0x72cebbf26f93cc5913fd87076c59428b794d6786", "config": "" }, "traits": [ { "trait_type": "Base", "value": "Starfish", "display_type": null, "max_value": null, "trait_count": 0, "order": null }, { "trait_type": "Eye", "value": "Big", "display_type": null, "max_value": null, "trait_count": 0, "order": null } ], "last_sale": null, "top_bid": null, "listing_date": null, "is_presale": false, "supports_wyvern": true, "rarity_data": null, "transfer_fee": null, "transfer_fee_payment_token": null, "related_assets": [], "orders": null, "auctions": [], "top_ownerships": [ { "owner": { "user": { "username": null }, "profile_img_url": "https://storage.googleapis.com/opensea-static/opensea-profile/2.png", "address": "0x72cebbf26f93cc5913fd87076c59428b794d6786", "config": "" }, "quantity": "3", "created_date": "2022-09-29T09:44:15.755541+00:00" } ], "ownership": null, "highest_buyer_commitment": null, "token_id": "0" }
.
solidity development
title generator
https://patorjk.com/
.
spdx license
// SPDX-License-Identifier: MIT
.
mumbai test contract
0x383A22a13D2693ecE63186A594671635a4C163fB
0 notes
Text
Routing using react-router-dom v6 in React.js
Routing using react-router-dom v6 in React.js
Hi, in this tutorial, we will talk about Routing using react-router-dom in React.js. We will cover BrowserRouter, Routes, Link, Dynamic Route, Outlet, useParams & useNavigate Hooks. Routing using react-router-dom The complete source code for a particular project is available on GitHub. I used to use Reach-router earlier for all my projects as it was a small, simple router for React…
View On WordPress
0 notes
Text
Koa crud operations - FE
Frontend
Frontend > src > components > AllProduct.js
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
const AllProdcut = () => {
const [product, setproduct] = useState();
const [serachItem, setserachItem] = useState([]);
useEffect(async () => {
try {
const data = await (
await axios.get("http://localhost:3003/products/all")
).data;
setproduct(data);
} catch (error) {
console.log(error);
}
}, []);
function deleteProduct(_id) {
axios
.delete("http://localhost:3003/products/" + _id)
.then((res) => {
console.log(res.data);
alert(" deleted");
})
.catch((err) => {
alert(err);
});
setproduct(product.filter((product) => product._id !== _id));
}
return (
<div className="container">
<br></br> <br></br> <br></br>
<Link to="/CreateProduct">
<button type="submit" className="btn btn-primary">
Add new Product
</button>
</Link>
<br></br> <br></br>
<div className="col-md-9">
<h4> Now You Can Search </h4>
<input
type="search"
class="form-control round"
placeholder="Search by id "
aria-label="Search"
onChange={(event) => {
setserachItem(event.target.value);
}}
aria-describedby="search-addon"
/>
</div>
<br></br>
<table className="table table-dark">
<thead className="">
<tr>
<th> ID</th>
<th>name</th>
<th>price </th>
<th>Description</th>
<th>update</th>
<th>delete</th>
</tr>
</thead>
<tbody>
{product &&
product
.map((product) => {
if (serachItem == "") {
return product;
} else if (
product.name.toLowerCase().includes(serachItem.toLowerCase())
) {
return product;
}
})
.map((product) => {
return (
<tr>
<td>{product._id}</td>
<td>{product.name}</td>
<td>{product.description}</td>
<td>{product.price}</td>
<td>
<a
className="btn btn-warning"
href={`/products/${product._id}`}
>
Update
</a>
</td>
<td>
<a
className="btn btn-warning"
onClick={() => {
deleteProduct(product._id);
}}
>
delete
</a>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default AllProdcut;
Frontend > src > components > CreateProduct.js
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
const CreateProduct = () => {
const [Product, setProduct] = useState({
name: "",
price: "",
description: "",
});
let navigate = useNavigate();
function sendData(e) {
e.preventDefault();
axios
.post("http://localhost:3003/products/add", Product)
.then(() => {
alert("New product Created");
navigate("/main");
})
.catch((err) => {
alert(err);
});
setProduct({
name: "",
price: "",
description: "",
});
}
function handleChange(event) {
const { name, value } = event.target;
setProduct((preValue) => {
return {
...preValue,
[name]: value,
};
});
}
return (
<div className="container">
<form onSubmit={sendData}>
<h1>Add new product</h1>
<div className="form-group row">
<label for="name" className="col-sm-3 col-form-label">
product Name
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id=""
name="name"
placeholder="Enter product Name"
onChange={handleChange}
value={Product.name}
/>
</div>
</div>
<div className="form-group row">
<label for="leaderITNum" className="col-sm-3 col-form-label">
price
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="price"
name="price"
placeholder="Enter price"
onChange={handleChange}
value={Product.price}
required
/>
</div>
</div>
<div className="form-group row">
<label for="topicName" className="col-sm-3 col-form-label">
Product description
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="description"
name="description"
placeholder="Enter description"
onChange={handleChange}
value={Product.description}
required
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-10">
<button type="submit" className="btn btn-primary">
<b>Add Product</b>
</button>
</div>
</div>
</form>
</div>
);
};
export default CreateProduct;
Frontend > src > components > Login.js
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { loginFunction } from "../services/LoginServices";
const Login = () => {
const navigate = useNavigate();
const [fromdata, setFromtdata] = useState({
email: "",
password: "",
});
const { email, password } = fromdata;
const OnChangeData = (e) => {
setFromtdata({ ...fromdata, [e.target.name]: e.target.value });
};
const submitdata = async (e) => {
e.preventDefault();
console.log("data", fromdata);
let data = await loginFunction(fromdata);
console.log("data", data);
if (data?.data?.token) {
localStorage.setItem("token", data?.data?.token);
localStorage.setItem("userRole", data?.data?.userRole);
navigate("/main");
} else {
alert("faild");
}
};
return (
<div>
<div>
<center>
<div>
<h2>Login to the system</h2>
</div>
<br />
<br />
<div>
<form className="form">
<input
type="email"
placeholder="Enter your email"
name="email"
value={email}
onChange={(e) => OnChangeData(e)}
/>
<br />
<br />
<input
type="password"
placeholder="Enter your password"
name="password"
value={password}
onChange={(e) => OnChangeData(e)}
/>
<br />
<br />
<button
className="btn btn-success"
onClick={(e) => submitdata(e)}
>
Login
</button>
</form>
</div>
<br />
<h4>Don't Have an account? Register Below</h4>
<a href="/RegisterUser" className="btn btn-primary">
Register
</a>
</center>
</div>
</div>
);
};
export default Login;
Frontend > src > components > Navbar.js
import React,{useEffect,useState} from "react";
import { useNavigate } from "react-router-dom";
const Navbar =()=>{
const navigate = useNavigate();
const [userRole, setuserRole] = useState(null);
useEffect(() => {
setuserRole(localStorage.getItem("userRole"));
}, [])
const LogOutfunc = (e)=> {
e.preventDefault();
localStorage.removeItem("token");
localStorage.removeItem("userRole");
navigate("/")
window.location.reload();
}
return (
<div> <div>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid">
<a className="navbar-brand" href="/main">Home</a>
<div className="collapse navbar-collapse" >
<div className="navbar-nav">
</div>
</div>
</div>
<button style={{display:userRole !== null ? "flex": "none" , float:"left" , marginLeft:"5px"}} onClick={(e)=>LogOutfunc(e)}>Log Out</button>
</nav>
</div></div>
)
}
export default Navbar;
Frontend > src > components > RegisterUser.js
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { RegisterUsers } from "../services/LoginServices";
const RegisterUser = () => {
const navigate = useNavigate();
const [formdata, setformdata] = useState({
name: "",
email: "",
password: "",
userRole: "",
});
const { name, email, password, userRole } = formdata;
const onChangedata = (e) => {
setformdata({ ...formdata, [e.target.name]: e.target.value });
};
const AddNewUser = async (e) => {
e.preventDefault();
try {
var data = await RegisterUsers(formdata);
console.log(data);
if (data?.data?.name) {
alert("Register success");
navigate("/");
} else {
navigate("/main");
}
} catch (error) {
console.log(error);
}
};
return (
<div>
{" "}
<div>
<center>
<div>
<h2>Register to the System</h2>
</div>
<br />
<br />
<div>
<form className="form">
<input
type="text"
placeholder="Enter your name"
name="name"
value={name}
onChange={(e) => onChangedata(e)}
/>
<br />
<br />
<input
type="email"
placeholder="Enter your email"
name="email"
value={email}
onChange={(e) => onChangedata(e)}
/>
<br />
<br />
<input
type="password"
placeholder="Enter your password"
name="password"
value={password}
onChange={(e) => onChangedata(e)}
/>
<br />
<br />
<label>select user role</label>
<br />
<select
class=""
onChange={(e) => onChangedata(e)}
name="userRole"
value={formdata.userRole}
>
<option value="customer">customer</option>
<option value="admin">admin</option>
</select>
<br />
<br />
<button
className="btn btn-success"
onClick={(e) => AddNewUser(e)}
>
Insert
</button>
<br></br>
<h4> Have an account? </h4>
<a href="/" className="btn btn-primary">
login
</a>
</form>
</div>
</center>
</div>
</div>
);
};
export default RegisterUser;
Frontend > src > components > UpdateProduct.js
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { useParams } from "react-router";
const UpdateProduct = () => {
const [Product, setProduct] = useState({
name: "",
price: "",
description: "",
});
let navigate = useNavigate();
const { id } = useParams();
useEffect(() => {
function getProduct() {
axios
.get(`http://localhost:3003/products/${id}`)
.then((res) => {
setProduct(res.data);
})
.catch((err) => {
alert(err.message);
});
}
getProduct();
}, []);
function sendData(e) {
e.preventDefault();
const UpdateProduct = Product;
axios
.put(`http://localhost:3003/products/${id}`, UpdateProduct)
.then(() => {
alert("updated success");
navigate("/");
})
.catch((err) => {
alert(err);
});
}
function handleChange(event) {
const { name, value } = event.target;
setProduct((preValue) => {
return {
...preValue,
[name]: value,
};
});
}
return (
<div className="container">
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<form onSubmit={sendData}>
<h1>update product</h1>
<div className="form-group row">
<label for="name" className="col-sm-3 col-form-label">
product Name
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id=""
name="name"
placeholder="Enter product Name"
onChange={handleChange}
value={Product.name}
/>
</div>
</div>
<div className="form-group row">
<label for="leaderITNum" className="col-sm-3 col-form-label">
price
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="price"
name="price"
placeholder="Enter price"
onChange={handleChange}
value={Product.price}
required
/>
</div>
</div>
<div className="form-group row">
<label for="topicName" className="col-sm-3 col-form-label">
Product description
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="description"
name="description"
placeholder="Enter description"
onChange={handleChange}
value={Product.description}
required
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-10">
<button type="submit" className="btn btn-primary">
<b>Update</b>
</button>
</div>
</div>
</form>
</div>
);
};
export default UpdateProduct;
Frontend > src > services > LoginServices.js
import axios from "axios";
const LoginURL = "http://localhost:3003/user/login";
const RegisterURL = "http://localhost:3003/user/register";
export async function loginFunction(data) {
let alldata = {
email: data.email,
password: data.password,
};
return await axios.post(LoginURL, alldata);
}
export async function RegisterUsers(data) {
var alldata = {
name: data?.name,
email: data?.email,
password: data?.password,
userRole: data?.userRole,
};
return await axios.post(RegisterURL, alldata);
}
Frontend > src > .gitignore
/node_modules/
Frontend > App.js
import { useEffect, useState } from "react";
import AllProdcut from "./components/AllProdcut";
import UpdateProduct from "./components/UpdateProduct";
import CreateProduct from "./components/CreateProduct";
import Login from "./components/Login";
import RegisterUser from "./components/RegisterUser";
import Navbar from "./components/Navbar";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
const App = () => {
const [loggedUser, setloggedUser] = useState(null);
useEffect(() => {
setloggedUser(localStorage.getItem("token"));
}, []);
return (
<div>
<Router>
<Navbar/>
{loggedUser !== null }
<Routes>
<Route
exact
path="/"
element={loggedUser !== null ? <AllProdcut /> : <Login />}
/>
<Route path="/main" element={<AllProdcut />} />
<Route path="/RegisterUser" element={<RegisterUser />} />
<Route path="/products/:id" element={<UpdateProduct />} />
<Route path="/CreateProduct" element={<CreateProduct />} />
</Routes>
</Router>
</div>
);
};
export default App;
Frontend > index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<App />,
document.getElementById("app")
);
Frontend > .gitignore
/node_modules/
Frontend > package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "react-scripts test",
"start": "parcel public/index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.27.2",
"cors": "^2.8.5",
"parcel": "^2.6.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.3.0"
},
"devDependencies": {
"buffer": "^6.0.3",
"process": "^0.11.10"
}
}
0 notes
Text
Concept of React Router
React Router is a powerful library that enables seamless navigation and routing in React applications. Understanding the core concepts of React Router is essential for building dynamic, user-friendly single-page applications. This guide covers the fundamental concepts and provides practical examples to help you master React Router.
Core Concepts of React Router
1. Router Component
The Router component is the foundation of React Router. It wraps your entire application and enables routing functionality.
BrowserRouter: Uses the HTML5 history API to keep your UI in sync with the URL.
HashRouter: Uses the hash portion of the URL (i.e., window.location.hash) to keep your UI in sync with the URL.
import { BrowserRouter } from 'react-router-dom';
function App() { return ( ); }
export default App;
2. Route Component
The Route component is used to define a mapping between a URL path and a component. It renders the specified component when the URL matches the path.
import { Route, Routes } from 'react-router-dom';
function App() { return ( } /> } /> } /> ); }
function Home() { return
Home Page
; }
function About() { return
About Page
; }
function Contact() { return
Contact Page
; }
3. Link Component
The Link component is used to create navigational links in your application. It works similarly to an HTML anchor tag but prevents full-page reloads.
import { Link } from 'react-router-dom';
function Navbar() { return ( Home About Contact ); }
4. useNavigate Hook
The useNavigate hook allows you to programmatically navigate to different routes.
import { useNavigate } from 'react-router-dom';
function Home() { const navigate = useNavigate();
const goToAbout = () => { navigate('/about'); };
return (
Home Page
Go to About ); }
5. Dynamic Routing
Dynamic routing allows you to pass parameters through the URL. This is useful for creating pages that depend on dynamic data, such as user profiles or product details.
import { useParams } from 'react-router-dom';
function App() { return ( } /> ); }
function User() { const { id } = useParams(); return
User ID: {id}
; }
6. Nested Routes
Nested routes allow you to define routes within other routes. This is particularly useful for layouts that require sub-sections, such as dashboards.
function Dashboard() { return (
Dashboard
} /> } /> ); }
function Profile() { return
Profile Page
; }
function Settings() { return
Settings Page
; }
7. Protected Routes
Protected routes restrict access to certain parts of your application based on authentication status.
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ element, isAuthenticated }) { return isAuthenticated ? element : ; }
function App() { const isAuthenticated = false; // Replace with actual authentication logic
return ( } /> } /> } />} /> ); }
8. Handling 404 Pages
Handling 404 pages ensures that users are informed when they navigate to an undefined route.
function NotFound() { return
404 Not Found
; }
function App() { return ( } /> } /> } /> ); }
Diagram: Basic React Router Flow
graph LR A[BrowserRouter] --> B[Routes] B --> C[Route path="/"] B --> D[Route path="/about"] B --> E[Route path="/contact"] B --> F[Route path="*"] C --> G[Home] D --> H[About] E --> I[Contact] F --> J[NotFound]
Conclusion
Mastering React Router is crucial for building efficient and user-friendly React applications. By understanding and utilizing its core concepts—such as Router, Route, Link, and dynamic routing—you can create a seamless navigation experience for your users. Explore these concepts further and practice implementing them to enhance your React development skills.
Hope you liked the article on React Router for any query visit: https://reactmasters.in/ or free demo sessions kindly contact us at Mob:+91 84660 44555
0 notes
Text
useNavigate & useLocation hooks react-router-dom-v6
https://vikasprogramming.blogspot.com/2022/01/usenavigate-uselocation-hooks-react.html
#ReactJs #redux #useLocation #useNavigate #react-router #react-router-dom #javascript #vikasprograming #programming #web #development #programming #webdeveloper #reacthooks #typescript #html #css #html5 #bootstrap #ui #designing #uidesigner #uidevelopment #route #routing #routes
0 notes