How to use ReactJS in Laravel - javascript

I am new to ReactJS and I am looking for a way to integrate it in Laravel. Is there any way that I can use React components within laravel views or it should be done only by using API as separate projects.

Use Laravel to provide the base view, but then after that all the views would be handled by React.Then Use Laravel as API and React as front-end. Also have a look at this blog

have a page as a root for react and do not forget to add every react page in web.php
Route::view('/courselist', 'app');
all your folders inside src should be copied into resources/js/react. then implement this in webpack.mix.js:
.js('resources/js/react', 'public/js/reactJs').react()
https://stackoverflow.com/a/66545875/13266927

To can use React Js with Laravel By creating Api's in laravel and later on integrating those APIs in react js project using Axios() or fetch() in react js. Steps to do it as follows:
Create Database in MySQL Database let's say using the name as "employees"
Install laravel, Create a new project in laravel and create a controller using the command
php artisan make:controller EmployeeController
Create Route in routes folder and inside it in api.php import controller using
use App\Http\Controllers\EmployeeController;
and then Create a route using:
Route::post('/employee',[EmployeeController::class,'employee']);
Create a function in EmployeeController named employee
and controller will be look like this as below:
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
function employee(Request $req){
$employee = new Employee;
$employee -> TName=$req->input("TName");
$employee -> TID=$req->input("TID");
$employee -> Cnic=$req->input("Cnic");
$employee -> Email=$req->input("Email");
$employee -> Designation=$req->input("Designation");
$employee -> DId=$req->input("DId");
$employee -> Gender=$req->input("Gender");
$employee -> Address=$req->input("Address");
$employee -> PhNumber=$req->input("PhNumber");
$employee -> Skill=$req->input("Skill");
$employee->save();
return $employee;
}
}
Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
public $timestamps=false;
}
After this test API http://127.0.0.1:8000/api/employee which was declared in api.php /employee in postman tool then later us this in react js project as below:
// import { useNavigate } from "react-router-dom";
// import { useState, useEffect } from "react";
import { useState } from "react";
import "./assignsubjectteacher.css";
// import Header from "./Header.js";
function Assignsubjectteacher() {
const [TName, setTName] = useState("");
const [TID, setTID] = useState("");
const [Cnic, setCnic] = useState("");
const [Email, setEmail] = useState("");
const [Designation, setDesignation] = useState("");
const [DId, setDId] = useState("");
const [Gender, setGender] = useState("");
const [Address, setAddress] = useState("");
const [PhNumber, setPhNumber] = useState("");
// const [IsHOD, setIsHOD] = useState("");
const [Skill, setSkill] = useState("");
async function assignsubjectteacher() {
// console.warn(name, department);
let item = {
TName,
TID,
Cnic,
Email,
Designation,
DId,
Gender,
Address,
PhNumber,
// IsHOD,
Skill,
};
// console.log(item);
let result = await fetch("http://127.0.0.1:8000/api/employee", {
method: "POST",
body: JSON.stringify(item),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
result = await result.json();
localStorage.setItem("user-info", JSON.stringify(result));
console.warn(result);
}
return (
<>
<div className="col-sm-8 offset-sm-3">
<div className="mt-10 col-sm-9 center">
<br />
<br />
<h2>Add Faculty</h2>
<input
type="text"
placeholder="Teacher's Name"
className="col-sm-12 form-control"
onChange={(e) => setTName(e.target.value)}
/>
<br />
<br />
<input
type="text"
placeholder="Teacher's ID"
className="col-sm-4 form-control"
onChange={(e) => setTID(e.target.value)}
/>
<input
type="text"
placeholder="Enter CNIC"
className="col-sm-4 form-control"
onChange={(e) => setCnic(e.target.value)}
/>
<input
type="email"
placeholder="Enter Email"
className="col-sm-4 form-control"
onChange={(e) => setEmail(e.target.value)}
/>
<br />
<br />
<input
type="text"
placeholder="Enter Designation"
className="col-sm-4 form-control"
onChange={(e) => setDesignation(e.target.value)}
/>
<input
type="text"
placeholder="Enter DId"
className="col-sm-4 form-control"
onChange={(e) => setDId(e.target.value)}
/>
<select
placeholder="Select Gender"
className="col-sm-4 form-control"
onChange={(e) => setGender(e.target.value)}
>
<option>Select Gender</option>
<option>Male</option>
<option>Female</option>
</select>
<br />
<input
type="text"
placeholder="Address"
className="form-control"
onChange={(e) => setAddress(e.target.value)}
/>
<br />
<br />
<input
type="tel"
placeholder="Phone"
className="col-sm-6 form-control"
onChange={(e) => setPhNumber(e.target.value)}
pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"
/>
<input
type="text"
placeholder="Enter Skill"
className="col-sm-6 form-control"
onChange={(e) => setSkill(e.target.value)}
/>
<br />
<br />
{/* <label for="IsHOD">IsHOD</label> */}
{/* <input
id="IsHOD"
type="checkbox"
onChange={(e) => setIsHOD(e.target.value)}
/> */}
<br />
<br />
<button onClick={assignsubjectteacher} className="btn btn-danger">
Add
</button>
</div>
</div>
</>
);
}
export default Assignsubjectteacher;

Related

Reactjs Usestate hook not sending data properlty to database

i know this is very easy question , but i am new with MERN technology. i am sending my data using React frontend to json-server npm module , all the codes works properly even though the data stored to backend smoothly . but the problem is that frontend data send extra fields to backend server which i don't want . you can see image there are 3 object 1st two object i have stored manually and third one i stored using React frontend application . the third one json-object stored extra fields are highlited here which i dont want . i am upload my working code please guide me .
//RegisterUser react Component :
import React from 'react'
import { useState } from 'react';
import loginImage from '../images/login2.jpeg';
import { NavLink } from 'react-router-dom';
import { addUser} from '../Service/api';
const initialValues = {
name:"",
username:"",
email:"",
phone:"",
}
const RegisterUser = () => {
const [user , setUser]= useState([initialValues]);
const { name,username, email, phone,} = user;
const style = {
color: 'black',
textAlign:'center'
};
const onValueChange= (e)=>{
console.log(e.target.Object);
setUser({...user, [e.target.name]:e.target.value})
console.log(user)
}
const addUserDetails= async()=>{
await addUser(user);
}
return (
<div>
<div>
<div className="container login-container">
<div className="row login-form-1">
<div className="col-md-6 ">
<h3 style={style}>Registration</h3>
<form>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="name" value={name} placeholder="Your Name *" />
</div>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="username" value={username} placeholder="username *" />
</div>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="email" value={email} placeholder="Your Email *" />
</div>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="phone" value={phone} placeholder="Mobile Number *" />
</div>
<div className="form-group">
<input type="submit" className="btnSubmit" onClick={()=> addUserDetails()} defaultValue="Login" />
</div>
</form>
</div>
<div className="col">
<img className="loginpic" src={loginImage} alt="login Image"/>
<div className="col">
<NavLink to="/login" className="signupIs" >I have already account</NavLink>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default RegisterUser
Api file
import axios from 'axios';
const url = 'http://127.0.0.1:3003/users';
export const getUsers = async ()=>{
return await axios.get(url);
}
export const addUser = async(user)=>{
return await axios.post(url,user);
}
again i am informing that the code is running no error while executing , but the issue is getting extra data field from React Frontend
When you first initialize your "user", you create it as an array:
const [user , setUser]= useState([initialValues]);
// ^---- here ---^
Then later you interpret the array as an object and add properties to it:
setUser({...user, [e.target.name]:e.target.value})
When doing so, that initial "user" would be a property called "0" since it's the first element of the array. So those "extra properties" are simply the initial state.
It sounds like what you intended was not to use an array at all:
const [user, setUser] = useState(initialValues);

reactjs clear file input field after submit

I'm trying to delete my file input field data from e.target but i need the rest of the e.target data to send to emailjs.
The problem is when user uploads a file in my form, the file is most of the time bigger than 50kb and this is the limit for my account on emailjs.
I don't need to send my file to emailjs but i need it to just be stored in my database.
I have tried to clear the form field before sending it to emailjs
with fileUpload.current.value = ""; but the data is still actief in
e.target.
This is e.target Data. i need the data to stay in this way in e.target to send to emailjs
<form class="Grade_inputForm__1lbhQ" autocomplete="off">
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="text" name="name" required="" class="Grade_input__22PTE" placeholder="Name*" maxlength="10">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="email" required="" name="email" class="Grade_input__22PTE" placeholder="Email*">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="text" name="Address" required="" class="Grade_input__22PTE" placeholder="Address*">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="tel" name="phone" class="Grade_input__22PTE" placeholder="Phone">
</div>
<div class="Grade_input_container__3ztZk css-vurnku">
<input type="file" class="Grade_input__22PTE" name="5349366.jpg">
</div>
<div class="Grade_textarea__YR0na css-vurnku">
<textarea name="cards" required="" class="Grade_input__22PTE">
</textarea>
</div>
<div class="Grade_textarea__YR0na css-vurnku">
<textarea name="message" class="Grade_input__22PTE" placeholder="Message">
</textarea>
</div>
<br>
<input type="submit" value="Send" class="Grade_btn__1QKUn">
</form>
how can i delete my file from e.target ?
import React, { useRef, useState } from "react";
import { jsx, Box } from "theme-ui";
import style from "../../style/Grade.module.css";
import { db, storage } from "../components/config/config";
import emailjs from "emailjs-com";
export default function GradeCards() {
const [file, setFile] = useState();
const name = useRef("");
const email = useRef("");
const Addres = useRef("");
const phone = useRef("");
const cards = useRef("");
const message = useRef("");
const fileUpload = useRef("");
const sendEmail = (e) => {
e.preventDefault();
//sending data to emailjs with e.target
emailjs
.sendForm(
"service account",
"template name",
e.target,
"user_id"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
};
const sendDataToDb = (e) => {
// sendEmail(e);
e.preventDefault();
e.persist(); // this is test when i use sendEmail() in .then()
const formData = new FormData(e.target);
const obj = {};
for (let [key, value] of formData.entries()) {
obj[key] = value;
}
if (file !== null) {
storage
.ref(`/files/${Date.now() + "-" + file.name}`)
.put(file)
.then(() => console.log("Succes"));
}
//this don't help in deleting data from e.target
delete obj[file.name];
db.collection("collectionName")
.add(obj)
.then(() => {
fileUpload.current.value = "";
})
.then(() => {
//test if the data is deleted her.But its still actief in e.target
console.log(e.target);
sendEmail(e);
})
.then(() => {
name.current.value = "";
email.current.value = "";
Addres.current.value = "";
phone.current.value = "";
cards.current.value = "";
message.current.value = "";
console.log("done sending");
});
};
return (
<section>
<Box className={style.container}>
<Box className={style.form}>
<Box className={style.contact_form}>
<form
onSubmit={(e) => sendDataToDb(e)}
className={style.inputForm}
autoComplete="off"
>
<Box className={style.input_container}>
<input
ref={name}
type="text"
name="name"
required
className={style.input}
placeholder="Name*"
maxLength="10"
/>
</Box>
<Box className={style.input_container}>
<input
ref={email}
type="email"
required
name="email"
className={style.input}
placeholder="Email*"
/>
</Box>
<Box className={style.input_container}>
<input
ref={Addres}
type="text"
name="Address"
required
className={style.input}
placeholder="Address*"
/>
</Box>
<Box className={style.input_container}>
<input
ref={phone}
type="tel"
name="phone"
className={style.input}
placeholder="Phone"
/>
</Box>
<Box className={style.input_container}>
<input
ref={fileUpload}
type="file"
name={file?.name}
onChange={(e) => {
setFile(e.target.files[0]);
}}
className={style.input}
/>
</Box>
<Box className={(style.input_container, style.textarea)}>
<textarea
ref={cards}
name="cards"
required
className={style.input}
></textarea>
</Box>
<Box className={(style.input_container, style.textarea)}>
<textarea
ref={message}
name="message"
className={style.input}
placeholder="Message"
></textarea>
</Box>
<br />
<input type="submit" value="Send" className={style.btn} />
</form>
</Box>
</Box>
</Box>
</section>
);
}
I don't know how you can set it here, but in general, if you have an input of type file and with name let's say image2, then you can do the following:
e.target["image2"].value = [];
this will empty the input.
See this sandbox
If you comment out the previous line of code, it will display the full details of the chosen file.
If you have this line there, it will display the object as it was never assigned a file from your disk.

handling events in react

I need to make a login page, when I click the submit button this should be navigated to Dashboard page. The below is my code, what is the problem in it. When I give details in the login page and click on login, the details vanishes and not navigated to dashboard.
import React, { Component, useState } from "react";
import axios from 'axios';
import { setUserSession } from '../utils/common';
function Login(props) {
const username = useFormInput('');
const password = useFormInput('');
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
// handle button click of login form
const handleLogin = () => {
props.history.push('/dashboard');
}
return (
<form>
<h3>Sign In</h3>
<div className="form-group">
<label>Email address</label>
<input type="email" className="form-control" placeholder="Enter email" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
{error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br />
<input type="button" className="btn btn-primary btn-block" value={loading ? 'Loading...' : 'Sign-in'} onClick={handleLogin} disabled={loading} /><br />
<p className="forgot-password text-right">
Forgot password?
</p>
</form>
);
}
const useFormInput = initialValue => {
const [value, setValue] = useState(initialValue);
const handleChange = e => {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
}
}
export default Login;
Do you have a route defined for /dashboard. Everything worked me in code sandbox without react router setup. Psuedo code shown below
<Switch>
<Route path="/dashboard">
<DashboardComponent />
</Route>
</Switch>

react-modal - onChange on input is not updating state

I hope you will be able to help me with an answer to my question. I am using react-modal and inside the modal I have an input where users can write an email. When writing the email it should update the state but that is not happening.
What is happening right now is that the model re-renders every time I write a new letter and that results in the state only updating with the first letter I typed and then focus is lost.
I am using react hooks. I know that changes a bit.
My code looks like the following:
import React, { useState, useContext } from 'react';
import AppContext from '../../AppContext.jsx';
import GroupContext from './GroupContext.jsx';
import Section from '../../Elements/PageContent/Section.jsx';
import PageTitle from '../../Elements/PageContent/PageTitle.jsx';
import WhiteContainer from '../../Elements/PageContent/WhiteContainer.jsx';
import { Form, FormGroup, FormSection, FormSection_Split, Label, Input, Select, Submit } from '../../Elements/Forms/FormCollection.jsx';
import { MusicGenres } from '../../Elements/Forms/MusicGenres.jsx';
import { Years } from '../../Elements/Forms/Years.jsx';
import { H3 } from '../../Elements/Fonts/FontCollection.jsx';
import { Icon } from '../../Elements/Image/ImageUtil.jsx';
import ReactModal from "react-modal";
import { useModal } from "react-modal-hook";
export default function Groups(props) {
const AC = useContext(AppContext);
const GC = useContext(GroupContext);
const [groupName, setGroupName] = useState("");
const [groupDescription, setGroupDescription] = useState("");
const [memberEmail, setMemberEmail] = useState("");
const [groupMembers, setGroupMembers] = useState([]);
const [showModal, hideModal] = useModal(() => (
<ReactModal className="DialogPopup" isOpen ariaHideApp={false}>
<Form>
<FormGroup>
<FormSection>
<Label htmlFor="memberEmail" title="Email of your group member:" />
<Input type="email" name="memberEmail" value={memberEmail} onChange={(e) => setMemberEmail(e.target.value)} placeholder="#" />
</FormSection>
</FormGroup>
</Form>
<button onClick={(e) => hideModal()} className="Close" aria-label="Close popup"><Icon iconClass="fal fa-times" /></button>
</ReactModal>
), []);
async function addObjectToGroupMembersArray(e) {
e.preventDefault();
console.log("Adding member");
}
return (
<React.Fragment>
<PageTitle title="Add group" />
<Section>
<Form>
<FormGroup>
<FormSection>
<WhiteContainer>
<Label htmlFor="groupName" title="Group name:" />
<Input type="text" name="groupName" value={groupName} onChange={(e) => setGroupName(e.target.value)} maxLength="60" required />
<span className="CharactersLeft">Characters left: {60 - groupName.length}</span>
</WhiteContainer>
</FormSection>
<FormSection>
<WhiteContainer>
<Label htmlFor="groupDescription" title="Describe your group:" />
<textarea name="groupDescription" id="groupDescription" value={groupDescription} onChange={(e) => setGroupDescription(e.target.value)} maxLength="500"></textarea>
<span className="CharactersLeft">Characters left: {500 - groupDescription.length}</span>
</WhiteContainer>
</FormSection>
<FormSection>
<WhiteContainer>
<Label htmlFor="groupMembers" title="List the emails of your group members?" />
<a href="#" className="AddLink" aria-label="Add member" title="Click to add a member" onClick={(e) => { e.preventDefault(); showModal(); }}>
<Icon iconClass="fal fa-plus" />
</a>
</WhiteContainer>
</FormSection>
<FormSection className="FormSection--Submit">
<Submit text="Create group" />
</FormSection>
</FormGroup>
</Form>
</Section>
</React.Fragment>
);
}
Does anyone of you know why the modal is updating every time I type, resulting in not being able to write anything in the input. Should i use "ref" and if I should, how would I do that?
The onChange method I am using is always working, just not inside react-modal.
I finally figured it out. It's because modal is working a little like the useEffect hook. If i add memberEmail to the bottom of the modal state, then it is working.
const [memberEmail, setMemberEmail] = useState("");
const [showModal, hideModal] = useModal(() => (
<ReactModal className="DialogPopup" isOpen ariaHideApp={false}>
<Form>
<FormGroup>
<FormSection>
<Label htmlFor="memberEmail" title="Email of your group member:" />
<Input type="email" name="memberEmail" value={memberEmail} onChange={(e) => setMemberEmail(e.target.value)} placeholder="#" />
</FormSection>
</FormGroup>
</Form>
<button onClick={(e) => hideModal()} className="Close" aria-label="Close popup"><Icon iconClass="fal fa-times" /></button>
</ReactModal>
), [memberEmail]);
What about creating an external function that you would call in onChange?
something like:
const handleOnChange = (event) => {
setMemberEmail(event.target.value);
}
// then call it in your component
<Input type="email" name="memberEmail" value={memberEmail} onChange={handleOnChange} placeholder="#" />

Cannot read property 'value' of null in ReactJS

I've been trying to console.log these 2 inputs, but can't seem to figure it out, can anyone tell me what I've done wrong?
I keep getting the Cannot read property 'value' of null error
function printInputs() {
let username = document.getElementById('user').value
let password = document.getElementById('pass').value
console.log(username);
console.log(password);
}
function App() {
return (
<div className="App">
<h1>Log In</h1>
<h1>{code}</h1>
<form>
<input className='userInput' id='user' type='text' placeholder='username' /><br />
<input className='userInput' id='pass' type='password' placeholder='password' /><br />
<input className='userSubmit' type='submit' value='Log In' onSubmit={printInputs()} />
</form>
</div>
);
}
onSubmit={printInputs()}
You are trying to call printInputs immediately (before the render function has returned anything so before the inputs are in the page).
You need to pass a function to onSubmit:
onSubmit={printInputs}
That said, this is not the approach to take for getting data from forms in React. See the Forms section of the React guide for the right approach.
The way to write forms in react. Working example demo
function App() {
const [state, setState] = React.useState({ username: "", password: "" });
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
const handleChange = e => {
setState({
...state,
[e.target.name]: e.target.value
});
};
return (
<div className="App">
<h1>Log In</h1>
<form onSubmit={handleSubmit}>
<input
className="userInput"
name="username"
type="text"
placeholder="username"
onChange={handleChange}
/>
<br />
<input
className="userInput"
name="password"
type="password"
placeholder="password"
onChange={handleChange}
/>
<br />
<input className="userSubmit" type="submit" value="Log In" />
</form>
</div>
);
}
in the first never use real dom to manipulate the dom in
React ,use a state to get de value and the onSumbit is used in Form tag
import React, { useState } from "React";
const App = () => {
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const printInputs = () => {
console.log(userName);
console.log(password);
};
return (
<div className="App">
<h1>Log In</h1>
<form onSubmit={printInputs}>
<input
className="userInput"
id="user"
type="text"
placeholder="username"
onChange={event => setUserName(event.target.value)}
/>
<br />
<input
className="userInput"
id="pass"
type="password"
placeholder="password"
onChange={event => setPassword(event.target.value)}
/>
<br />
<input
className="userSubmit"
type="submit"
value="Log In"/>
</form>
</div>
);
};
export default App;

Categories

Resources