I am currently working on a component to update routines. I am recieving the error message that activity is undefined, and I think I know that the problem is that I was trying to use it before defining it, but everywhere I try to put the .map() causes the code to break. Here's what the file looks like:
import React, { useState, useEffect, Fragment } from "react";
import { getAllActivities } from "../api";
import { attachActivityToRoutine } from "../api";
const UpdateRoutine = ({ routineData, setIsShown }) => {
const handleChange = (event) => {
setValue(event.target.value);
};
const [allActivities, setAllActivities] = useState([]);
console.log(allActivities, 'line 10')
return (
<div>
<form onSubmit>
<label htmlFor="updateRoutine">Update Name:</label>
<input />
<button type="submit">Submit</button>
</form>
<form onSubmit>
<label htmlFor="updateGoal">Update Goal:</label>
<input></input>
<button type="submit">Submit</button>
</form>
<form onSubmit="handleSubmit">
<fieldset>
<label htmlFor="selectActivity">
Activity <span className="selectActivity">({allActivities})</span>
</label>
(v This select is the problem area v)
<select
name="activity"
id="selectActivity"
value={activity}
onChange={(event) => setAllActivities(event.target.value)}
>
{getAllActivities.map((activity, idx) => (
<option key={`${idx}:${activity.name}`} value={activity.name}>
{activity.name}
</option>
))}
</select>
</fieldset>
<button type="submit">Search</button>
</form>
<button
onClick={(event) => {
setIsShown(false);
}}
>
Nevermind
</button>
</div>
);
};
export default UpdateRoutine;
Any advice would be greatly appreciated!
Related
What could be wrong with these codes? The input is not working once I add [event.target.name]. If I remove that line of codes, I can see the contents that I type inside the input box. The issue is that I want it to work with this code [event.target.name]. This will enable me pick each inputbox values as entered by the user. There are three input boxes and I need to capture the three values in my useState. Any help on how to write it better?
import React, { useState } from 'react';
import "./addbirthday.css";
import "./home.css";
export default function Addbirthday({setShowAdd}) {
const [inputDatas, setInputData] = useState([
{fullName: '', fullDate: '', relationship: ''}
]);
const handlePublish = () =>{
console.log("Hi ", inputDatas)
}
const handleChangeInput = (index, event) =>{
const values = [...inputDatas];
values[index][event.target.name] = event.target.value
setInputData(values)
}
return (
<div className="container">
<div className= { closeInput? "addContainer" :"addWrapper homeWrapper "}>
<i className="fas fa-window-close" onClick={closeNow} ></i>
{inputDatas.map((inputData, index)=> (
<div key={index} className="addbirth">
<label>Name</label>
<input type="text" name="Fname" placeholder='Namend' value=
{inputData.fullName} onChange = {event => handleChangeInput(index, event)} />
<label>Date</label>
<input type="date" placeholder='Date' name="fdate" value=
{inputData.fullDate} onChange = {event => handleChangeInput(index, event)} />
<label>Relationship</label>
<input type="text" placeholder='Friend' name="frelationship" value=
{inputData.relationship} onChange = {event => handleChangeInput(index, event)}/>
</div>
))}
<button className="addBtn" onClick={handlePublish} >Add</button>
</div>
</div>
)
}
You are not setting the name correctly
Change your input tags name to same as state object name meaning
<input name='fullname' />
I have modified your code a bit. Make it as your own and get it done
Upvote my answer if it helps
https://codesandbox.io/s/jolly-khayyam-51ybe?file=/src/App.js:0-1711
import React, { useState } from "react";
export default function Addbirthday({ setShowAdd }) {
const [inputDatas, setInputData] = useState([
{ Fname: "", fdate: "", frelationship: "" }
]);
const handlePublish = () => {
console.log("Hi ", inputDatas);
};
const handleChangeInput = (index, event) => {
const values = [...inputDatas];
values[index][event.target.name] = event.target.value;
setInputData(values);
console.log(values[index][event.target.name]);
};
return (
<div className="container">
<div className={"addContainer addWrapper homeWrapper"}>
<i className="fas fa-window-close"></i>
{inputDatas.map((inputData, index) => (
<div key={index} className="addbirth">
<label>Name</label>
<input
type="text"
name="Fname"
placeholder="Namend"
value={inputData.fullName}
onChange={(event) => handleChangeInput(index, event)}
/>
<label>Date</label>
<input
type="date"
placeholder="Date"
name="fdate"
value={inputData.fullDate}
onChange={(event) => handleChangeInput(index, event)}
/>
<label>Relationship</label>
<input
type="text"
placeholder="Friend"
name="frelationship"
value={inputData.relationship}
onChange={(event) => handleChangeInput(index, event)}
/>
</div>
))}
<button className="addBtn" onClick={handlePublish}>
Add
</button>
</div>
</div>
);
}
I am creating a simple todo list. In here there is a modal for the update form,I can take the relevant values from the state And set them to the input field values. then I can't edit the input fields. I think the problem is with the onChange function or value property
import React from 'react'
import {useRef,useState,useEffect} from 'react'
import {FaTimes} from 'react-icons/fa'
export const Modal = ({edData,showModal,setShowModal,onAdd,setEd,tasks}) => {
const [text,setText] = useState('')
const[day,setDay] = useState('')
const[reminder,setReminder] = useState(false)
useEffect(() => {
if(edData!=null){
for(let i=0;i<tasks.length;i++)
{
if(tasks[i].id===edData){
// console.log(tasks[i])
setText(tasks[i].text)
setDay(tasks[i].day)
setReminder(tasks[i].reminder)
}
}
}
// inputText.current.value = edData.text;
// inputDay.current.value = edData.day;
// inputReminder.current.value = edData.reminder;
});
const closeModal = () =>{
setEd(null)
setShowModal(prev=>!prev)
setText('')
setDay('')
setReminder(false)
}
const onSubmit = (e) =>{
e.preventDefault()
if (!text){
alert('Please add a task')
return
}
onAdd({text,day,reminder})
setText('')
setDay('')
setReminder(false)
setShowModal(prev=>!prev)
}
return (
<>
{showModal?
<div className="background">
<div className="ModalWrapper" >
<div className="ModalContent">
<h2 className="modalTitle">{edData==null? 'Add New Task':'Update Task'}</h2>
<form className="add-form" onSubmit={onSubmit}>
<div className="form-control">
<label htmlFor="">Task</label>
<input type="text" placeholder="Add Task" name="" id="" value={text} onChange={(e) => setText(e.target.value)}/>
</div>
<div className="form-control ">
<label htmlFor="">Date & Time</label>
<input type="text" placeholder="Add Date and Time" name="" id="" value={day} onChange={(e) => setDay(e.target.value)}/>
</div>
<div className="form-control form-control-check">
<label htmlFor="">Set Reminder</label>
<input type="checkbox" checked={reminder} name="" id="" value={reminder} onChange={(e) => setReminder(e.currentTarget.checked)}/>
</div>
<input className="btn btn-block" type="submit" value="Save Task" />
</form >
</div>
<div className="CloseModalButton" onClick={closeModal}>
<FaTimes/>
</div>
</div>
</div>
: null}
</>
)
}
If you don't pass a dependency array to useEffect it will be called on every render, calling setText inside of it and overwriting the input's value, pass an empty array to useEffect if you don't want it to run on every render :
useEffect(() => {
// ....
}, []);
Hi I am trying to create a react-redux form and my e.preventDefault() is not working which i causing a redirect everytime I press an enter key.
Could someone look in my code and tell me where am I going wrong:
I am having an input field and when I am giving an e.preventDefault(), but for some reason its redirecting.
import React, { useState } from "react";
import { useDispatch } from "react-redux";
function InputField() {
let [task, setTask] = useState("");
const dispatch = useDispatch();
let onTaskAdd = (e) => {
setTask(e.target.value);
};
let addTaskinTaskManager = () => {
dispatch({ type: "ADD_TASK", payload: task });
setTask("");
};
return (
<div className="container-fluid mt-5">
<div className="row justify-content-center">
<div className="col-md-6">
<form>
<div className="form-group row">
<label className="col-md-2 col-form-label">Task:</label>
<div className="col-md-10">
<input
type="text"
id="task"
name="task"
className="form-control"
placeholder="eg, singing"
value={task}
onChange={(e) => {
e.preventDefault();
e.stopPropagation();
onTaskAdd(e);
}}
/>
</div>
</div>
</form>
</div>
<div className="col-md-2">
<button
type="button"
onClick={addTaskinTaskManager}
className="btn btn-primary"
>
Add Task
</button>
</div>
</div>
</div>
);
}
export default InputField;
I was working with checkboxes type input in the form. Just want to know the way I am handling it, Is it the right way or not?
Code:
import React from 'react';
import { AiOutlineSearch } from "react-icons/ai";
import { useScroll } from '../custom_hook/useScroll';
const SearchBar = ({ totalPrograms, programs, setPrograms, isLoading }) => {
const scrolled = useScroll();
const handleSubmit = (event) => {
event.preventDefault();
const searchProgramName = document.getElementById('search').value;
if(searchProgramName) {
setPrograms(
programs.filter(program =>
program.name.toLowerCase().includes(searchProgramName)
)
);
}
else {
handleClick();
}
}
const handleClick = () => {
const allPhase = document.getElementsByName('phase');
const checkedPhaseValue = [];
allPhase.forEach(phase => {
if(phase.checked) {
checkedPhaseValue.push(phase.value);
}
});
setPrograms(checkedPhaseValue.length ?
totalPrograms.filter(
program => checkedPhaseValue.includes(program.phase.toLowerCase())
)
: totalPrograms
);
}
return (
<header className={`container header header-sb ${scrolled && 'h-shadow'}`}>
<form className="container container-center" onSubmit={handleSubmit}>
<div className="type-search">
<AiOutlineSearch className="icon"/>
<input id="search" disabled={isLoading} type="search" placeholder="search by program name"/>
</div>
<div className="checkbox-container">
<div className="d-inline">
<input type="checkbox" disabled={isLoading} onClick={handleClick} name="phase" id="open_application" value="application_open"/>
<label htmlFor="open_application">Open Application</label>
</div>
<div className="d-inline">
<input type="checkbox" disabled={isLoading} onClick={handleClick} name="phase" id="application_in_review" value="application_review"/>
<label htmlFor="application_in_review">Application in Review</label>
</div>
<div className="d-inline">
<input type="checkbox" disabled={isLoading} onClick={handleClick} name="phase" id="in_progress" value="in_progress"/>
<label htmlFor="in_progress">in Progress</label>
</div>
<div className="d-inline">
<input type="checkbox" disabled={isLoading} onClick={handleClick} name="phase" id="completed" value="completed"/>
<label htmlFor="completed">Completed</label>
</div>
</div>
</form>
</header>
)
}
export default SearchBar;
The work I have to do is :
● Once the list is loaded, the user can now search through the page based on two
parameters:
The name of the program
Filter on the stage of the programs
● Once the user applies this filter+search then the page should pick out the programs
and show the result set (the filter is to be done on the front end and not a separate
server call)
In my app, I am making a form to add animal for adoption with React. The data is stored in Mongo if this is important to know.
But I can not figure out how, I tried to look and nothing works for me. Maybe there is something wrong with the form. I would be very thankful if someone can tell me how to clear or reset the form after submitting. I simplified it so it would be easy to see what I have. Here is my form:
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { addAnimal } from "../redux/actions";
const AddAnimalForm = () => {
const dispatch = useDispatch();
const [name, setName] = useState("");
const [kind, setKind] = useState("");
const [displayForm, setDisplayForm] = useState(false);
const dispatchAddAnimal = () => {
dispatch(
addAnimal(
{
name,
kind
},
"_id name kind sex age city author phone info"
)
);
};
const onShowButtonClicked = () => {
setDisplayForm(true);
};
const onHideButtonClicked = () => {
setDisplayForm(false);
};
return !displayForm ? (
<button className="col-xs-12 col-md-3" onClick={onShowButtonClicked}>
add
</button>
) : (
<React.Fragment>
<div className="col-xs-12 col-sm-9">
<button className="col-xs-12 col-md-3" onClick={onHideButtonClicked}>
hide{" "}
</button>
<form>
<div className="form-row">
<div className="form-group col-md-6">
<label htmlFor="animal-name">name</label>
<input
type="text"
className="form-control"
onChange={e => setName(e.target.value)}
id="animal-name"
/>
</div>
<div className="form-group col-md-6">
<label htmlFor="kind">kind</label>
<input
type="text"
onChange={e => setKind(e.target.value)}
className="form-control"
id="kind"
/>
</div>
</div>
<button
type="button"
className="btn btn-primary"
onClick={dispatchAddAnimal}
>
add animal
</button>
</form>
</div>
</React.Fragment>
);
};
export default AddAnimalForm;
define a variable at the top just below you imports
let exampleRef = React.createRef()
hi first you have to create a reference to that form like this :-
<form ref={(el) => myFormRef = el;}>
<input />
<input />
...
<input />
</form>
and after that, while submitting your form you just use the reset() method provided by the form reference like this
const dispatchAddAnimal = () => {
myFormRef.reset();
dispatch(
addAnimal(
{
name,
kind
},
"_id name kind sex age city author phone info"
)
);
};
let me know if it works for you or not.
there is also a great library React Advanced Form which handle lots of thing on its own like validation and other stuff check this out if you feel free