Need to Pass props to other components in hook - javascript

i want to pass a prop from one(App.jsx) component to other component(form.jsx) in state hooks
App.jsx
import React, {useEffect, useState} from 'react';
import Form from './components/Form';
import Table from './components/Table';
import axios from 'axios';
const App = () => {
const [data, setData] = useState({data:[]});
const [editData, setEditData] = useState([]);
const create = (data) => {
axios.post('http://localhost:5000/info',data).then((res) =>{
getAll();
})
}
useEffect(() =>{
getAll();
},[])
const getAll = () =>{
axios.get("http://localhost:5000/info").then((response) =>{
setData({
data:response.data
})
})
}
const update = event =>{
setEditData(data)
console.log(data); // THIS "data" is the prop that i need to pass to Form.jsx component
}
return (
<div>
<div>
<Form myData={create} editForm={editData} />
</div>
<div>
<Table getData={data} edit={update} />
</div>
</div>
);
};
export default App;
i want that "data" value form App.jsx component as props in this Form.jsx component
Form.jsx
import React, {useState} from 'react';
const Form = (props) => {
const [formData, setFormData] = useState({ Name:'', Age:'', City:''});
const infoChange = e => {
const { name,value} = e.target;
setFormData({
...formData,
[name]: value,
})
}
const infoSubmit = e =>{
e.preventDefault();
let data={
Name:formData.Name,
Age:formData.Age,
City:formData.City
}
props.myData(data);
}
const componentWillReceive = (props) => { // i want the props data here
console.log(props.data); // in class component they use componentWillReceiveRrops ,
} // is there any alternative for function based component to receive props?
return (
<div>
<form onSubmit={infoSubmit} autoComplete="off">
<div>
<label>Name:</label>
<input type="text" onChange={infoChange} name="Name" value={formData.Name} placeholder="Enter Name" />
</div>
<div>
<label>City:</label>
<input type="text" onChange={infoChange} name="City" value={formData.City}
placeholder="Enter City" />
</div>
<div>
<label>Age:</label>
<input type="text" onChange={infoChange} name="Age" value={formData.Age} placeholder="Enter Age" />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default Form;
i have commented the area of problem within the code , you can ignore the return () block of code.
Sorry for silly questions but THANKYOU Very Much !!! in advance

Use the following code in Form.jsx, the useEffect will listen the change of props.data and update the value
useEffect(() => {
setFormData(props.data);
},
[props.data]);
For more information, you may check the following answer
https://stackoverflow.com/a/65842783/14674139

Related

Unable to get input type text name in Reactjs

I am working with Reactjs and nextjs,Right now i am trying to get input type text value but right now i am not getting any value(name is empty during alert), here is my current code
import dynamic from 'next/dynamic';
import React, { FormEventHandler, useRef } from 'react';
import { useEffect, useState } from "react";
import axios from 'axios';
export default function Testform() {
const [state, setState] = useState({ name: '' });
const [Name, setName] = useState('');
const handleChange = (event:any) => setState({...state, name: event.target.value })
const submitHandler: FormEventHandler<HTMLFormElement> = async (event) => {
event.preventDefault();
const name = Name;
alert('name is '+ name);
}
return (
<form className="forms-sample" onSubmit={submitHandler}>
<div className='flex-dvs'>
<div className="form-group">
<h3>Blog title</h3>
<input type="text"
className="form-control"
id="exampleInputName1"
placeholder="Title"
name="name"
value={state.name}
onChange={handleChange}
/>
</div>
</div>
<div className='save-btn text-right'>
<button className='btn btn-primary mr-2'>Save</button>
</div>
</form>
)
}
You are setting the state variable. So use state.name instead of Name
const name = state.name;

Next.js trying to push data from input value into json, but onSubmit doesn't work at all

I'm trying to put input value into json file, but submit button doesn't work, can you help me with it?
import PcosData from "/data/pcos.json";
import {useEffect} from "react";
import { useState } from "react";
export default function adminPcos() {
// const CreateMePanel = () => {
const [title, setTitle] = useState(PcosData["pcos-first"].title);
const [time, setTime] = useState(PcosData["pcos-first"].time);
const handleSubmit = (e) => {
PcosData["pcos-first"].title = title;
PcosData["pcos-first"].time = time;
}
return (
<div>
<h1>hello world</h1>
{PcosData["pcos-first"].map((pcosdata) => (
<form onSubmit={handleSubmit} key={ pcosdata.id } method="post">
<input type="text" name={title} defaultValue={pcosdata.title} onChange={(e) => setTitle({text: e.target.value})}/>
<input type="text" name={time} defaultValue={pcosdata.time} onChange={(e) => setTime({text: e.target.value})}/>
<input type="submit" value="submit"/>
</form>
))}
</div>
)
}
i checked all of the functions, variables, but didn't find any errors

ReactJS Error input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`

I have a super simple React page connecting to NodeJS endpoints. I'm getting this error "Uncaught Error: input is a void element tag and must neither have children nor use dangerouslySetInnerHTML."
I have tried multiple solutions posted in SOF(put a label outside the input tag, use self close input tags, etc.) and all around but nothing helped.
EmailFaxDetails.js
import React, { useState } from 'react'
import FetchOrderDetails from './FetchOrderDetails';
import '../App.css';
const EmailFaxDetails = () => {
const [message, setMessage] = useState('');
const [isShown, setIsShown] = useState(false);
const handleChange = event => {
setMessage(event.target.value);
console.log(event.target.value);
};
const handleClick = event => {
event.preventDefault();
setIsShown(true);
console.log(message);
}
return(
<div>
<br></br>
<br></br>
Order Number: <input placeholder="Order Number" type="text" id="message" name="message" onChange={handleChange} value={message} autoComplete="off" />
<button onClick={handleClick}>Search</button>
{isShown && <FetchOrderDetails ord_no={message}/>}
</div>
)
}
export default EmailFaxDetails;
FetchOrderDetails.js
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import '../App.css';
const FetchOrderDetails = ({ord_no}) => {
const [data, setData] = useState([]);
const url = `http://localhost:5000/api/customerOrder/${ord_no}`
useEffect(() => {
axios.get(url)
.then(response => {
console.log(response.data)
setData(response.data)
})
.catch((err) => console.log(err));
}, [url]);
if(data) {
return(
<div>
{data.map((order) => (
<div key={order.ID}>
<br></br>
<br></br>
Sales Ack Email: <input placeholder="Sales Ack Email" id="salesAck">{order.cmt[0]}</input>
<br></br>
Invoice Email: <input placeholder="Invoice Email" id="salesInv">{order.cmt[1]}</input>
<br></br>
<br></br>
<div>
<button>Update</button>
</div>
</div>
))}
</div>
)
}
return (
<h1>Something went wrong, please contact IT!</h1>
)
}
export default FetchOrderDetails;
App.js
import React from 'react';
import EmailFaxDetails from './components/EmailFaxDetails';
import './App.css';
function App() {
return (
<>
<EmailFaxDetails />
</>
);
}
export default App;
In the FetchOrderDetails.js
Sales Ack Email: <input placeholder="Sales Ack Email" id="salesAck">{order.cmt[0]}</input>
<br></br>
Invoice Email: <input placeholder="Invoice Email" id="salesInv">{order.cmt[1]}</input>
input element is a self-closing tag and can't contain children elements or text.
If you want to add a default value for the input you can add defaultValue property.
Sales Ack Email: <input defaultValue={order.cmt[0]} placeholder="Sales Ack Email" id="salesAck" />
<br></br>
Invoice Email: <input defaultValue={order.cmt[1]} placeholder="Invoice Email" id="salesInv" />
Or add a value property and onChange event to update the value.

local storage is not persistent in react app

I am creating a react app which is using local storage. I am saving and array of objects to local storage.
when I try to save to local storage the data is saving.
and then when I refresh the page the saved data is becoming empty object,
like this [].
if any one knows why its happening please help me
import React, {useEffect, useState} from 'react';
import Addcontact from './Addcontact';
import './App.css';
import Contactlist from './Contactlist';
import { Header } from './Header';
function App() {
const keyy ="contactlist"
const [contacts, setcontacts] = useState([])
const contactshandler = (contact)=> {
console.log(contact)
setcontacts([...contacts, contact])
}
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])
useEffect(() => {
localStorage.setItem(keyy, JSON.stringify(contacts));
}, [contacts])
return (
<div className="ui container">
<Header />
<Addcontact contacts={contacts} contactshandler={contactshandler} />
<Contactlist contacts={contacts} />
</div>
);
}
app component
import React, { useState } from 'react'
function Addcontact({contacts, setcontacts, contactshandler}) {
const [user, setuser] = useState({username:'', email:''})
const addvalue = (e) => {
e.preventDefault();
console.log(user)
contactshandler(user)
setuser({username:'', email:''})
}
return (
<div>
<div className='ui main'>
<h2> Add Contact</h2>
<form className='ui form' onSubmit={addvalue}>
<div className=''>
<label>name</label>
<input name="name" placeholder='name' value={user.username} onChange={(e) => setuser({...user, username : e.target.value })} />
</div>
<div className='feild'>
<label>email</label>
<input email='email' placeholder='email' value={user.email} onChange={(e) => setuser({...user, email: e.target.value})} />
</div>
<button>add</button>
</form>
</div>
</div>
)
}
export default Addcontact
export default App;
add component
this is the value showing when saving after refresh this value becomes empty object
enter image description here
console
enter image description here
You don't need useEffect to read the data. You can initially read it.
const [contacts, setcontacts] = useState(JSON.parse(localStorage.getItem(keyy)) ?? [])
and remove
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])

Passing useState using createContext in React.tsx

I have defined a context Transaction which takes an object and a function.
In AppProvider Transaction.Provider is returned.
The code is of GlobalState.tsx file:
import { createContext, useState } from "react";
export interface IProviderProps {
children?: any;
}
type Cat = {
id: number;
text: string;
amount: number;
}
type Ca =Cat[]
export const initialState = {
state: [
{id:4, text:'hi', amount:234},
{id:3, text:'hd', amount:-234},
{id:1, text:'hs', amount:34}
],
setState: (state: Ca) => {}
}
console.log(initialState.state)
export const Transaction = createContext(initialState);
export const AppProvider = (props: IProviderProps) => {
const [state, setState] = useState(initialState.state);
console.log(state);
return <Transaction.Provider value={{state, setState}}>{props.children}</Transaction.Provider>;
};
In App.tsx I have passed the Provider:
import React, { useState } from 'react';
import './App.css';
import { Header } from "./Components/Header";
import { Balance } from './Components/Balance';
import { IncomeExpense } from "./Components/Income_Expense";
import { TransactionHistory } from "./Components/TransactionHistory";
import { AddTransaction } from "./Components/AddTransaction";
import { AppProvider } from './Context/GlobalState'
function App() {
const [islit, setlit] = useState(true);
return (
<AppProvider>
<div className={`${islit? '': 'dark'} body`}>
<Header islit={islit} setlit={setlit} />
<div className="container">
<Balance />
<IncomeExpense />
<TransactionHistory />
<AddTransaction />
</div>
</div>
</AppProvider>
);
}
export default App;
I am trying to change 'state' with 'setState' but it is not working:
import React, { useState, useContext } from 'react';
import { Transaction} from '../Context/GlobalState';
export const AddTransaction = () => {
const initialState = useContext(Transaction);
const [Incexp, setIncExp] = useState('income');
const [text, settext] = useState('');
const [amount, setamount] = useState(0);
const transactions = initialState.state;
const settransaction = initialState.setState;
function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
transactions.push({id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount})
settransaction(transactions);
console.log(transactions);
}
return (
<div>
<h3>Add Transaction</h3>
<form onSubmit={Addition}>
<label htmlFor="description">Text</label>
<input type="text" id="description" placeholder="Enter description..." value={text} onChange={(e) => { settext(e.target.value) }} required />
<label htmlFor="amount">Amount</label>
<input type="number" id="amount" placeholder="Enter Amount..." value={amount === 0 ? '' : amount} onChange={(e) => { setamount(parseInt(e.target.value)) }} required />
<div className="Inc-Exp">
<div>
<input type="radio" id="income" name="balance" defaultChecked onClick={()=>{setIncExp('income')}}/>
<label htmlFor="income" className="inc-col">Income</label>
</div>
<div>
<input type="radio" id="expense" name="balance" onClick={()=>{setIncExp('expense')}}/>
<label htmlFor="expense" className="exp-col">Expense</label>
</div>
</div>
<input className="btn" type="submit" value="Addtransaction" />
</form>
</div>
)
}
Another child component:
import React, { useContext } from 'react';
import { Transaction } from '../Context/GlobalState';
export const Balance = () => {
const initialState = useContext(Transaction);
const transactions = initialState.state;
var total=0;
transactions.map((transaction) => total+=transaction.amount)
return (
<div>
<h4>Your Balance</h4>
<h1 className={`${total > 0 ? 'plus' : ''} ${total < 0 ? 'minus' : ''}`}>${total}</h1>
</div>
)
}
Every time I click on a button Add Transaction. I want it to update state. but it is not updating.
The state is not update because you are not changing the reference of the object transactions, do it like below
function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
settransaction([...transactions,{id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount} ]);
console.log(transactions);
}
In this case the object you pass to settransaction will have a new reference the react will update the state
Please change setState to a callback variant setState((previousState) => {...}) as:
function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
transactions.push({id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount})
settransaction(transactions);
console.log(transactions);
}
to
function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
settransaction((prevState) => {
return prevState.push({id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount});
});
}
The console.log may not show updated value, as re-render would be required to get updated context value.
But after context update a re-render would going to be trigger by react, and thus the component responsible to show updated state will eventually display the updated state.

Categories

Resources