In this code, I want to upload the radio button value and store it in firebase database.I want use the simplest way to solve that. I see other code will use constructor but I do not know whether I can use simpler way to solve it. how can I do that ?
import React, { useState } from "react";
import ReactPlayer from "react-player";
import Array from "../Array";
import firebase from "firebase";
export default () => {
const [selected, setSelected] = useState("");
return (
<div>
<div className="video">
<ReactPlayer url={Array[0]} playing />
</div>
<label>Guess whether this video is fake or real ?</label> <br />
<label>
<input
type="radio"
name="answer"
value="real"
onChange={e => setSelected(e.target.value)}
/>
real
</label>
<label>
<input
type="radio"
name="answer"
value="fake"
onChange={e => setSelected(e.target.value)}
/>
fake
</label>
</div>
);
};
I would do it like this:
import React from "react";
....
export default () => {
const [state, setState] = React.useState({});
const handleInputChange = e => {
const { name, value } = e.target;
console.log(name, value);
setState(state => {
const newState = { ...state, [name]: value }
//post newState to firebase
return newState
});
};
return (
<div>
<div className="video">
<ReactPlayer url={Array[0]} playing />
</div>
<div>{JSON.stringify(state)}</div>
<label>Guess whether this video is fake or real ?</label> <br />
<label>
<input
type="radio"
name="answer1"
value="real"
onChange={handleInputChange}
/>
real
</label>
<label>
<input
type="radio"
name="answer2"
value="fake"
onChange={handleInputChange}
/>
fake
</label>
</div>
);
};
Related
I am not getting the choosen program option to select user,The props supposed to communicate from program.js to enrollmentform can anyone help me figuring out why the choosen program is not appearing
the code is --:
My App.js Code is ---:
import './App.css';
import EnrollmentForm from './EnrollmentForm';
function App() {
return (
<div className="App">
<EnrollmentForm >Just React</EnrollmentForm>
</div>
);
}
export default App;
My enrollmentform.js code is ---:
import { useState } from "react";
import "./App.css";
function EnrolmentForm(props) {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [welcomeMessage, setWelcomeMessage] = useState("");
const handleSubmit = (event) => {
setWelcomeMessage(`Welcome ${firstName} ${lastName}`);
event.preventDefault();
};
return (
<div>
<form className="enrolForm" onSubmit={handleSubmit}>
<h1>{props.chosenProgram} Student Details</h1>
<label>First name:</label>
<input
type="text"
name="fname"
onBlur={(event) => setFirstName(event.target.value)}
/>
<br />
<label>Last name:</label>
<input
type="text"
name="lname"
onBlur={(event) => setLastName(event.target.value)}
/>
<br />
<br />
<input type="submit" value="Submit" />
<br />
<label id="studentMsg" className="message">
{welcomeMessage}
</label>
</form>
</div>
);
}
export default EnrolmentForm;
my program.js code is ---:
import "./App.css";
import EnrolmentForm from "./EnrolmentForm";
import { useState } from "react";
function App() {
const [program, setProgram] = useState("UG");
const handleChange = (event) => {
setProgram(event.target.textContent);
};
return (
<div className="App">
<div className="programs">
<label>Choose Program:</label>
<select className="appDropDowns"
onChange={handleChange}
value={program} >
<option value="UG">Undergraduate</option>
<option value="PG">Postgraduate</option>
</select>
</div>
<EnrolmentForm chosenProgram={program} />
</div>
);
}
The desired output supposed to be--->
and the output which I am getting
There supposed to be a option of choosen program but it is not working and not apearing when I run the code
Your Code Should Look like This:
In App.js:
import './App.css';
import Program from './Program';
function App() {
return (
<div className="App">
<Program />
</div>
);
}
export default App;
In Enrollment.js code:
import { useState } from "react";
import "./App.css";
function EnrolmentForm(props) {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [welcomeMessage, setWelcomeMessage] = useState("");
const handleSubmit = (event) => {
setWelcomeMessage(`Welcome ${firstName} ${lastName}`);
event.preventDefault();
};
return (
<div>
<form className="enrolForm" onSubmit={handleSubmit}>
<h1>{props.chosenProgram} Student Details</h1>
<label>First name:</label>
<input
type="text"
name="fname"
onBlur={(event) => setFirstName(event.target.value)}
/>
<br />
<label>Last name:</label>
<input
type="text"
name="lname"
onBlur={(event) => setLastName(event.target.value)}
/>
<br />
<br />
<input type="submit" value="Submit" />
<br />
<label id="studentMsg" className="message">
{welcomeMessage}
</label>
</form>
</div>
);
}
export default EnrolmentForm;
And Program.js code:
import { useState } from "react";
import "./App.css";
import EnrolmentForm from "./EnrolmentForm";
function Program() {
const [program, setProgram] = useState("UG");
const handleChange = (event) => {
setProgram(event.target.textContent);
};
return (
<div className="App">
<div className="programs">
<label>Choose Program:</label>
<select
className="appDropDowns"
onChange={handleChange}
value={program}
>
<option value="UG">Undergraduate</option>
<option value="PG">Postgraduate</option>
</select>
</div>
<EnrolmentForm chosenProgram={program} />
</div>
);
}
export default Program;
Unable to get values in console!
What am I doing it incorrectly?
Attached below is the functional component of React
The Handler Functions
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
formSubmissionHandler should have on the form element rather than the div element.
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
What I am trying to do is when the user click the edit button, this will send him to a new page where he can modify the info he already entered. The problem I am facing is that the new page is not showing the data previously entered, so that the user can make his changes. Also, the submit button to send those changes is not working. These are the errors I am getting: src\components\RestaurantList.jsx
Line 25:8: React Hook useEffect has a missing dependency: 'setRestaurants'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Line 31:19: 'response' is assigned a value but never used no-unused-vars
src\components\UpdateRestaurant.jsx
Line 9:12: 'restaurants' is assigned a value but never used no-unused-vars
Line 38:8: React Hook useEffect has a missing dependency: 'code'. Either include it or remove the dependency array react-hooks/exhaustive-deps
My code for the component I am working on:
import React, {useState, useContext, useEffect} from 'react';
import { useHistory, useParams } from 'react-router-dom';
import RestaurantFinder from '../apis/RestaurantFinder';
import { RestaurantsContext } from '../context/RestaurantsContext';
const UpdateRestaurant = (props) => {
const {code} = useParams();
const {restaurants} = useContext(RestaurantsContext);
let history = useHistory();
const [name, setName] = useState("");
const [value, setValue] = useState ("");
const [strain, setStrain] = useState ("");
const [weight, setWeight] = useState ("");
const [authors, setAuthors] = useState ("");
const [number, setNumber] = useState ("");
const [page, setPage] = useState ("");
const [date, setDate] = useState ("");
useEffect(() => {
const fetchData = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setName(response.data.data.restaurant.name);
setValue(response.data.data.restaurant.value);
setStrain(response.data.data.restaurant.strain);
setWeight(response.data.data.restaurant.weight);
setAuthors(response.data.data.restaurant.authors);
setNumber(response.data.data.restaurant.number);
setPage(response.data.data.restaurant.page);
setDate(response.data.data.restaurant.date);
};
fetchData();
}, []);
const handleSubmit = async(e) => {
e.preventDefault();
const updatedRestaurant = await RestaurantFinder.put(`/${code}`, {
name,
value,
strain,
weight,
authors,
number,
page,
date,
});
console.log(updatedRestaurant);
history.push("/");
};
return (
<div>
<form action="">
<div className="form-group">
<label htmlFor="name">Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} code="name" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Value">Value</label>
<input value={value} onChange={(e) => setValue(e.target.value)} code="value" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Strain">Strain</label>
<input value={strain} onChange={(e) => setStrain(e.target.value)} code="strain" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Weight">Weight</label>
<input value={weight} onChange={(e) => setWeight(e.target.value)} code="weight" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Author">Author</label>
<input value={authors} onChange={(e) => setAuthors(e.target.value)} code="authors" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Number">Number</label>
<input value={number} onChange={(e) => setNumber(e.target.value)} code="number" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="Page">Page</label>
<input value={page} onChange={(e) => setPage(e.target.value)} code="page" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="date">Date</label>
<input value={date} onChange={(e) => setDate(e.target.value)} code="date" className="form-control" type="number" />
</div>
<button onClick={handleSubmit} type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
export default UpdateRestaurant
for reusable code, it may be best to just do something like this.
This is probably not the answer, but I hope it helps you find out the answer.
const [data, setData ] = useState({restraunt.loaded:"false"});
useEffect(() => {
const fetch = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setData({...response.data.data, restraunt.loaded:"true"});
};
fetch();
},[Data.restraunt.loaded])
const {name, value , page, loaded } = Data.restaurant;
return (
<div><h1>{loaded}</h1>
</div>
)
If it shows loaded as false then you know it is because of the data not loading.
I am aiming for new tasks to show as user clicks "add task", simple I know, but still learning react.
My goal was to use a ternary operator until its no longer null, and then map through the array each time a user clicks add task.
Issue:
I believe the renderTasks array isn't set by the time it tries to map over it, I get an error...
renderTasks.map is not a function
Is there a way I could utilize the useEffect for what I am trying to do, or any better ideas that could help? Thanks
Here's the code snippet of App.js
function App() {
const [tasks, setTasks] = useState([]);
const [renderTasks, setRenderTasks] = useState(null);
const handleAddTask = () => {
setRenderTasks(tasks);
};
const handleOnChange = (e) => {
setTasks({
...tasks,
[e.target.name]: e.target.value,
});
};
return (
<>
<div className="overview">
<label className="my-todos">My Todos</label>
<div className="input-div">
<div className="input-container">
<label className="title-desc">Title</label>
<input
name="title"
onChange={handleOnChange}
className="input-values"
type="text"
></input>
</div>
<div className="input-container">
<label className="title-desc">Description</label>
<input
name="description"
onChange={handleOnChange}
className="input-values"
type="text"
></input>
</div>
<button onClick={handleAddTask} className="add-task">
Add Task
</button>
</div>
{renderTasks !== null ? (
<ul>
{renderTasks.map((x) => {
return <li>{x.title - x.description}</li>;
})}
</ul>
) : null}
</div>
</>
);
}
export default App;
There were few issues in your implementation like how you destructing tasks, trying to access an object as an array and abusing the useState. You don't need useEffect or two useState to do the trick.
import React from "react";
import React, { useState } from 'react';
import "./style.css";
function App() {
const [tasks, setTasks] = useState([]);
const task = {};
const handleOnChange = (e) => {
task[e.target.name] = e.target.value;
};
const onClickHandler = (e)=>{
(task.title) && setTasks( [...tasks, task]);
}
return (
<>
<div className="overview">
<label className="my-todos">My Todos</label>
<div className="input-div">
<div className="input-container">
<label className="title-desc">Title</label>
<input
name="title"
onChange={handleOnChange}
className="input-values"
type="text"
></input>
</div>
<div className="input-container">
<label className="title-desc">Description</label>
<input
name="description"
onChange={handleOnChange}
className="input-values"
type="text"
></input>
</div>
<button onClick={onClickHandler} className="add-task">
Add Task
</button>
</div>
<ul>
{tasks.map((x) => {return <li>{x.title} - {x.description}</li> })}
</ul>
</div>
</>
);
}
export default App;
Even though you are initialising tasks to be an array, in handleOnChange you are setting it to an Object like this -
setTasks({
...tasks,
[e.target.name]: e.target.value,
});
This same tasks object you are trying to set for renderTasks in handleAddTask. So renderTasks is assigned to an Object and not an array and only arrays have map function and hence you are facing the issue renderTasks.map is not a function error
Try doing
Object.keys(renderTasks).map((x) => {
return <li>{x.title - x.description}</li>;
})
I was trying to implement contactUS form in react using hooks.Contact us form is placed inside hooks.When I first submit the form the state in hooks are not updated ,when I click 2nd time states are set .and I am returning state to class component there api call are made.
//contactushook.js
import React, { useState } from 'react';
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
setData({ name: document.getElementById('name').value, email: document.getElementById('email').value, message: document.getElementById('message').value });
console.log(data);
parentCallBack(data);
}
return <React.Fragment>
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input id="name" type="text" placeholder="enter the name"></input>
</div>
<div>
<input id="email" type="email" placeholder="enter the email"></input>
</div>
<div>
<textarea id="message" placeholder="Type message here"></textarea>
</div>
<button type="submit" >Submit</button>
</form>
</div>
</React.Fragment >
}
export default ContactUshook;
//contactus.js
import React, { Component } from 'react';
import ContactUshook from './hooks/contactushook';
import '../contactUs/contactus.css';
class ContactComponent extends Component {
onSubmit = (data) => {
console.log('in onsubmit');
console.log(data);
}
render() {
return (
<div>
<h4>hook</h4>
<ContactUshook parentCallBack={this.onSubmit}></ContactUshook>
</div>
);
}
}
export default ContactComponent;
Stop using document queries and start using state instead!
Your ContactUshook component should look like this:
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState({ name: '', email: '', message: '' });
const handleSubmit = () => {
event.preventDefault();
parentCallBack(data);
}
const handleChange = (event, field) => {
const newData = { ...data };
newData[field] = event.target.value;
setData(newData);
}
return (
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input
id="name"
type="text"
value={data.name}
placeholder="enter the name"
onChange={(e) => handleChange(e,'name')} />
</div>
<div>
<input
id="email"
type="email"
value={data.email}
placeholder="enter the email"
onChange={(e) => handleChange(e,'email')} />
</div>
<div>
<textarea
id="message"
value={data.message}
placeholder="Type message here"
onChange={(e) => handleChange(e,'message')} />
</div>
<button type="submit" >Submit</button>
</form>
</div>
);
}