Every time I click on the radio buttons, they don't get selected with the blue mark. I would like to know what I'm doing wrong here. This is the code:
import { useState } from "react";
const Form = () => {
const [clicked, setClick] = useState("v_likely");
const clickedRadio = () => {
setClick(clicked);
}
return (
<div className="form">
<div className="radio_button" style={{ fontSize: "12px" }}>
<label>Would you recommend to a friend?</label>
<div className="radio">
<div>
<input type="radio" name="v_likely" value={clicked} checked={clicked === "v_likely"} onClick={clickedRadio}></input>
<label>Very Likely</label>
</div>
<div>
<input type="radio" name="likely" value={clicked} checked={clicked === "likely"} onClick={clickedRadio}></input>
<label>Likely</label>
</div>
<div>
<input type="radio" name="think" value={clicked} checked={clicked === "think"} onClick={clickedRadio}></input>
<label>Will Think</label>
</div>
<div>
<input type="radio" name="no" value={clicked} checked={clicked === "no"} onClick={clickedRadio}></input>
<label>Not At All</label>
</div>
</div>
</div>
</div>
);
}
export default Form;
You are not updating clicked only assigning again same value.
To be able to run below is the code snippet.
import { useState } from "react";
const Form = () => {
const [clicked, setClick] = useState("v_likely");
const clickedRadio = (event) => {
setClick(event.target.name);
}
return (
<div className="form">
<div className="radio_button" style={{ fontSize: "12px" }}>
<label>Would you recommend to a friend?</label>
<div className="radio">
<div>
<input type="radio" name="v_likely" value={clicked} checked={clicked === "v_likely"} onClick={clickedRadio}></input>
<label>Very Likely</label>
</div>
<div>
<input type="radio" name="likely" value={clicked} checked={clicked === "likely"} onClick={clickedRadio}></input>
<label>Likely</label>
</div>
<div>
<input type="radio" name="think" value={clicked} checked={clicked === "think"} onClick={clickedRadio}></input>
<label>Will Think</label>
</div>
<div>
<input type="radio" name="no" value={clicked} checked={clicked === "no"} onClick={clickedRadio}></input>
<label>Not At All</label>
</div>
</div>
</div>
</div>
);
}
export default Form;
You should pass the event parameter to the clickedRadio function and use the name of the target to update the value:
const clickedRadio = (e) => {
setClick(e.target.name);
};
Related
Why filter by search work but by drop-down list not?
I don't know why this is so, maybe someone sees some error.
I would like to filter tags using checkboxes. It was hard for me to find a tutorial on the internet, I was able to find filtering by searching. It turned out that everything was set up successfully, then I wanted to set filtering by list, but here I have a problem. I don't know why the list search doesn't work - even though it seems to work on the console.
demo here:
https://codesandbox.io/s/adoring-wu-rt4wd?file=/src/styles.css
const [filterParam, setFilterParam] = useState(['All'])
const [q, setQ] = useState('')
const [searchParam] = useState(['tags'])
function search(data) {
return data.filter((item) => {
if (item.tags == filterParam) {
return searchParam.some((newItem) => {
return (
item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
)
})
} else if (filterParam == 'All') {
return searchParam.some((newItem) => {
return (
item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
)
})
}
})
}
return (
<>
<div>
<label htmlFor='search-form'>
<input
type='search'
name='search-form'
id='search-form'
className='search-input'
placeholder='Search for...'
value={q}
onChange={(e) => setQ(e.target.value)}
/>
<span className='sr-only'>Search countries here</span>
</label>
</div>
<div className='select'>
<select
onChange={(e) => {
setFilterParam(e.target.value)
// console.log(setFilterParam(e.target.value.toString()))
console.log(e.target.value.toString())
}}
aria-label='Filter Countries By Region'
>
<option value='All'>All</option>
<option value='accessibility'>accessibility</option>
<option value='javascript'>javascript</option>
<option value='css'>css</option>
<option value='advanced'>advanced</option>
<option value='svg'>svg</option>
</select>
</div>
<section className={styles.main}>
{search(data).map((item) => (
<div className={styles.card}>
<div>
<div className={styles.card__first}>
<div className={styles.card__name}>
<FaTwitter className={styles.card__icon} />
<span className={styles.card__author}>{item.authorId}</span>
</div>
<div className={styles.card__price}>
<p>{item.price}</p>
</div>
</div>
<div className={styles.card__title}>
<h1>{item.title}</h1>
</div>
<div>
<p className={styles.card__desc}>{item.description}</p>
</div>
</div>
<div className={styles.card__tags}>
{item.tags.map((t) => {
return (
<div className={styles.card__tag}>
<p>{t}</p>
</div>
)
})}
</div>
</div>
))}
</section>
</>
)
}
export default Page
You have to change a lot of things, you can try this example
import "./styles.css";
import { useState, useEffect } from "react";
import styles from "./App.module.css";
export default function App() {
const [data, setData] = useState([]);
const [filterParam, setFilterParam] = useState("All");
const [q, setQ] = useState("");
const [searchParam, setSearchParam] = useState([]);
const getData = () => {
fetch("data.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
})
.then(function (response) {
console.log(response);
return response.json();
})
.then(function (myJson) {
console.log(myJson);
setData(myJson);
});
};
useEffect(() => {
getData();
}, []);
function search(data) {
return data.filter(
(item) =>
(filterParam === "All" || item.tags.includes(filterParam)) &&
(searchParam.length === 0 ||
(searchParam.every((tag) => item.tags.includes(tag)) &&
JSON.stringify(item).toLowerCase().indexOf(q.toLowerCase()) > -1))
);
}
const inputChangedHandler = (event) => {
const value = event.target.value;
const index = searchParam.indexOf(value);
if (index > -1) {
const updatedParam = [...searchParam];
updatedParam.splice(index, 1);
setSearchParam(updatedParam);
} else {
setSearchParam([...searchParam, event.target.value]);
}
};
return (
<>
<div>
<label htmlFor="search-form">
<input
type="search"
name="search-form"
id="search-form"
className="search-input"
placeholder="Search for..."
value={q}
onChange={(e) => setQ(e.target.value)}
/>
<span className="sr-only">Search countries here</span>
</label>
</div>
<div className="select">
<select
onChange={(e) => {
setFilterParam(e.target.value);
// console.log(setFilterParam(e.target.value.toString()))
console.log(e.target.value.toString());
}}
aria-label="Filter Countries By Region"
>
<option value="All">All</option>
<option value="accessibility">accessibility</option>
<option value="javascript">javascript</option>
<option value="css">css</option>
<option value="advanced">advanced</option>
<option value="svg">svg</option>
</select>
</div>
<div>
<input
type="checkbox"
id="topping"
name="advanced"
value="advanced"
onChange={inputChangedHandler}
/>
advanced
</div>
<div>
<input
type="checkbox"
id="topping"
name="javascript"
value="javascript"
onChange={inputChangedHandler}
/>
javascript
</div>
<div>
<input
type="checkbox"
id="topping"
name="fundamentals"
value="fundamentals"
onChange={inputChangedHandler}
/>
fundamentals
</div>
<div>
<input
type="checkbox"
id="topping"
name="css"
value="css"
onChange={inputChangedHandler}
/>
css
</div>
<div>
<input
type="checkbox"
id="topping"
name="svg"
value="svg"
onChange={inputChangedHandler}
/>
svg
</div>
<div>
<input
type="checkbox"
id="topping"
name="accessibility"
value="accessibility"
onChange={inputChangedHandler}
/>
accessibility
</div>
<section className={styles.main}>
{search(data).map((item) => (
<div className={styles.card}>
<div>
<div className={styles.card__first}>
<div className={styles.card__name}>
<p className={styles.card__icon}>ICON</p>
<span className={styles.card__author}>{item.authorId}</span>
</div>
<div className={styles.card__price}>
<p>{item.price}</p>
</div>
</div>
<div className={styles.card__title}>
<h1>{item.title}</h1>
</div>
<div>
<p className={styles.card__desc}>{item.description}</p>
</div>
</div>
<div className={styles.card__tags}>
{item.tags.map((t) => {
return (
<div className={styles.card__tag}>
<p>{t}</p>
</div>
);
})}
</div>
</div>
))}
</section>
{/* <Margins>
<Header data={data} />
<Main data={data} />
</Margins> */}
</>
);
}
enter link description here
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)
this is the class based radio group . I want to convert it to functional based radio group. how can i do it. the code is as below:
import React, { Component } from "react";
class Demo2 extends Component {
constructor() {
super();
this.state = {
name: "React"
};
this.onValueChange = this.onValueChange.bind(this);
this.formSubmit = this.formSubmit.bind(this);
}
onValueChange(event) {
this.setState({
selectedOption: event.target.value
});
}
formSubmit(event) {
event.preventDefault();
console.log(this.state.selectedOption)
}
render() {
return (
<form onSubmit={this.formSubmit}>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={this.state.selectedOption === "Male"}
onChange={this.onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={this.state.selectedOption === "Female"}
onChange={this.onValueChange}
/>
Female
</label>
</div>
i want it working code for functional based component. i am new to react pls help.
Create a local state using React.useState and change the template based on the updated state.
*Note:- this operator is not needed for functional components.
And also you can return the template directly (no render method required)
Sample code:
import React, { useState } from "react";
import "./styles.css";
export default function Demo2() {
const [selectedOption, setSelectedOption] = useState("Male");
const onValueChange = (event) => {
setSelectedOption(event.target.value);
};
const formSubmit = (event) => {
event.preventDefault();
console.log(selectedOption);
};
return (
<form onSubmit={formSubmit}>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={selectedOption === "Male"}
onChange={onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={selectedOption === "Female"}
onChange={onValueChange}
/>
Female
</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
);
}
Working code - https://codesandbox.io/s/bold-platform-yr3l9?file=/src/App.js:0-1001
import React, { useState } from "react";
function Demo2() {
const [checked, setChecked] = useState("Male");
const onValueChange = (event) => {
setChecked(event.target.value);
};
const formSubmit = (event) => {
event.preventDefault();
console.log(checked);
};
return (
<form onSubmit={formSubmit}>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={checked === "Male"}
onChange={onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={checked === "Female"}
onChange={onValueChange}
/>
Female
</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
);
}
I am a beginner in react. I was working on the react function component with forms using hooks. Can anyone please tell how can I apply validation on email text when it is invalid or empty, and disable the continue button if the form is not valid.
import React, { useState } from "react";
const ForgotPassowrd = () => {
const [emailId, setemailId] = useState("");
const forgotPasswordClick = (event) => {};
return (
<div>
<div className="NewPassword-form form_wrapper">
<div className="form-body">
<form action="#">
<div>
<div className="form-group">
<label htmlFor="password">Email-Id</label>
<div className="input-group">
<input type="text" className="form-control" value={emailId} onChange={(event)=>
setemailId(event.target.value)}/>
</div>
</div>
<button type="button" onClick={forgotPasswordClick} className="btn btn-lg
btn-block">Continue</button>
</div>
</form>
</div>
</div>
</div>
);
};
export default ForgotPassowrd;
**Try it.This may be helpfull for you! If you can any queries comment below.**
const LoginV2 = ({}) => {
// state
const [loginForm, setLoginForm] = useState({
email: undefined,
password: undefined,
emailValid: false,
passwordValid: false,
});
const [error, setError] = useState({ email: undefined, password: undefined });
// state update
const handleLoginForm = (e) => {
checkValidity(e.target.name, e.target.value);
setLoginForm({ ...loginForm, [e.target.name]: e.target.value });
};
// validation function
const checkValidity = (inputName, inputValue) => {
switch (inputName) {
case "email":
let pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
loginForm.emailValid = pattern.test(inputValue);
break;
case "password":
loginForm.passwordValid = inputValue.length >= 6;
break;
default:
break;
}
};
// form submit
const onSubmitLoginForm = () => {
console.log(loginForm);
if (!loginForm.emailValid) {
setError(prevError => {
return {
...prevError,
email: "Invalid Email Address"
}
});
}
if (!loginForm.passwordValid) {
setError(prevError => {
return {
...prevError,
password: "Password must be at least six characters long"
}
});
}
return (
<div class="row">
<div class="form">
<div class="col span-1-of-2">
<div class="username">
<p class="login-para text-align-center">LOG IN VIA EMAIL</p>
<form method="post" action="#" class="login-form">
{error.email && (
<div class="alert alert-danger">
<p>
{" "}
<strong> {alertText} </strong> {error.email}
</p>
</div>
)}
{error.password && (
<div class="alert alert-danger">
<p>
{" "}
<strong> {alertText} </strong> {error.password}
</p>
</div>
)}
<div class="info-box">
{icon && <i class="fas fa-user-alt login-icon"></i>}
<input
type="text"
name="email"
placeholder="Your Email"
onChangeText={(e) => handleLoginForm(e)}
inputValue={loginForm.email}
/>
</div>
<div class="info-box">
{icon && <i class="fas fa-user-alt login-icon"></i>}
<input
type="password"
name="password"
placeholder="Your Password"
onChangeText={(e) => handleLoginForm(e)}
inputValue={loginForm.password}
/>
</div>
<div class="buttons">
<input type="checkbox" />
<label class="remember" for="#">
Remember me
</label>
<div class="form-btn-disabled" onClick={onSubmitLoginForm}
>
LOGIN NOW
</div>
</div>
</form>
</div>
</div>
</div>
</div>
);
};
export default LoginV2;
Try below. I have added inline comments for better understanding. Comment your queries if you have any.
// Regex to check valid email
const validEmail = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/g
import React, { useState } from "react";
const ForgotPassowrd = () => {
const [emailId, setemailId] = useState("");
//State to disable/enable continue button
const [disableBtn, setDisableBtn] = useState(false);
const forgotPasswordClick = (event) => {};
const handleSubmit = e => {
e.preventDefault();
// Do whatever you want to do after you click submit button
}
const handleChange = e => {
setemailId(event.target.value);
setDisableBtn(validEmail.test(e.target.value));
}
return (
<div>
<div className="NewPassword-form form_wrapper">
<div className="form-body">
{/* Remove action and use onSubmit handler*/}
<form onSubmit={handleSubmit}>
<div>
<div className="form-group">
<label htmlFor="password">Email-Id</label>
<div className="input-group">
{/* Introduced name attribute to help you with handleSubmit handler*/}
<input name="email" type="text" className="form-control" value={emailId} onChange={(event)=>
setemailId(event.target.value)}/>
</div>
</div>
<button onClick={forgotPasswordClick} className="btn btn-lg
btn-block" disabled={disableBtn}>Continue</button>
</div>
</form>
</div>
</div>
</div>
);
};
export default ForgotPassowrd;
I try to implement renderField for radio buttons, i can display it but when i click on radio field does not fill.
When i check the console, value of input is equal to undefined, always !
This is my code :
render(){
const {input, array, meta, label} = this.props;
return(
<div className="input-row">
<div className="radio-box">
{array.map((option,i) =>
<div className="radio-field" key={i}>
<input type='radio' name={option.name} onChange={() => {input.onChange('oui')}} value={option.value} checked={input.value === option.value} />
{/* Try this before <input type='radio' {...input} name={option.name} value={option.value} checked={input.value == option.value}/> */}
<label>{option.name}</label>
</div>
)}
</div>
</div>
)
}
I call this with :
<Field name="courtage" type="radio" label="Courtage ?" component={renderRadioField} array={selectOptions.courtage} {...courtage} />
SelectOptions.courtage is an array of object.
After few hours, I find a solution, I play with the state :
setRadioState(a) {
const obj = {};
obj[a.target.name] = a.target.value;
this.setState(obj);
}
render(){
const {input, array, meta, label, name} = this.props;
return(
<div className="input-row">
<div className="label-box">
<label>{label}</label>
</div>
<div className="radio-box">
{array.map((option,i) =>
<div className="radio-field" key={i}>
<input type='radio' name={name} {...input} onChange={this.setRadioState.bind(this)} value={option.value} checked={this.state.name} />
<label>{option.name}</label>
</div>
)}
{/* <div className="errors">{meta.touched && ((error && <span>{error}</span>))}</div> */}
</div>
</div>
)