Toggle Switch unable to maintain the set value when onClicked - reactjs

I want a toggle switch when onClicked would set thew current boolean value to its opposite. When the toggle button is clicked it sets to false but reverts back to true. I added a event.preventDefault to stop the refresh; however, though im getting the correct set value and stopped it from reverting back to default state when onClicked, the toggle no longer toggles left to right.
function CreateForm() {
const [isPrivate, setPrivate] = useState(true);
const handleStatus = (event) => {
// event.preventDefault();
setPrivate(!isPrivate)
console.log(isPrivate)
}
return (
<div className='createform__switch'>
<h5 className='createform__private'>Private</h5>
<label className="switch" htmlFor="checkbox" onClick={handleStatus}>
<input type="checkbox" id="checkbox" />
<div className="slider round"></div>
</label>
<h5 className='createform__public'>Public</h5>
</div>
)
}
how can I stop the value from reverting back to its default state but at the same time have a functioning animated toggle switch.
please, any help will be great

When you click on the checkbox you are calling the handleStatus method which changes the isPrivate value and then you are logging the value in the console. The thing is, that the isPrivate state is not been updated until the method execution is finished, so you are seeing the previous value in the console.
So the handleStatus method will look like this:
const [isPrivate, setPrivate] = useState(true);
const handleStatus = () => {
setPrivate(!isPrivate)
console.log(!isPrivate)
}
I also leave you some fixes of the code:
<div className='createform__switch'>
<h5 className='createform__private' style={{fontWeight: isPrivate ? "bolder" : "lighter"}}>Private</h5>
<input type="checkbox" id="checkbox" checked={isPrivate} onChange={handleStatus} />
<h5 className='createform__public' style={{fontWeight: isPrivate ? "lighter" : "bolder"}}>Public</h5>
</div>

Related

How to set radio button 'checked' based on value from database? - React

I have a radio button group in a component. I want to set which radio is selected based on it's value taken from the database in an Update/Edit scenario.
export default function updateRadioSelection(){
const [radioValue, setRadiovalue] = useState("");
useState(()=>{
setRadiovalue("pick"); // <-- Assume this value is taken from database, value may be either "delivery" or "pick"
}, [])
const changeSelection = (e)=>{
setRadiovalue(e.target.value);
}
return(
<div>
<input type="radio" id="delivery" name="orderType" value="delivery" required onChange={changeSelection} />
<label htmlFor="delivery">Delivery</label>
<input type="radio" id="pick" name="orderType" value="pick" onChange={changeSelection} />
<label htmlFor="pick">Pick Up</label>
</div>
)
}
To make a checkbox or radio checked you must use the checked prop for the input element, it receives a boolean value. And you can do something like this
export default function updateRadioSelection(){
const [radioValue, setRadiovalue] = useState("");
// useState will not execute any kind of callback function, for this case you need to use useEffect
useEffect(() => {
const dbResult = getRadioFromDb();
setRadiovalue(dbResult);
}, [])
const changeSelection = (e)=>{
setRadiovalue(e.target.value);
}
return(
<div>
<input type="radio" id="delivery" name="orderType" value="delivery" required onChange={changeSelection} checked={radioValue === 'delivery'} />
<label htmlFor="delivery">Delivery</label>
<input type="radio" id="pick" name="orderType" value="pick" onChange={changeSelection} checked={radioValue === 'pick'} />
<label htmlFor="pick">Pick Up</label>
</div>
)
}
You can read more about radio input in its documentation
Just a few minutes after posting this question I found the answer I was searching for. Turns out it's pretty easy.
Just add checked={radioValue === "pick"} for the Pick Up radio button & the same for other radio button by replacing "pick" with "delivery"
reference - react.tips/radio-buttons-in-reactjs

Issue with submitting the form when the button in search bar is clicked in react

I am having issue with when a user inputs a value in the search bar and click the button it either throws an error in the console (Uncaught (in promise) SyntaxError: Unexpected token U in JSON at position 0) and the value passed to the handleSubmit is undefined. However, I am able to pass the value when I hit the enter button as keyPress function please let me know what I am doing wrong and thank you in advance!
SearchBar.js
const Navbar = ({ searchBarText, setSearchBarText }) => {
function handleSubmit(e){
console.log('submitted Value', e.target.value);
setSearchBarText(e.target.value)
e.preventDefault();
}
function keyPress(e){
if(e.keyCode === 13 || e.key === 'Enter' ){
console.log('value', e.target.value);
setSearchBarText(e.target.value)
// put the login here
e.preventDefault();
}
}
return (
<>
<nav className="navbar navbar-expand-lg navbar-light bg-light ">
<form onSubmit={handleSubmit}>
<div className="search-container" >
<span className="search-icon-btn">
<button className="search-icon-btn" type="submit" onClick={handleSubmit} >
<i className="fa fa-search" value={searchBarText}></i>
</button>
</span>
<div className="search-input">
<input
type="text"
className="search-bar"
placeholder="Search...."
onKeyDown={keyPress}
/>
</div>
</div>
</form>
</nav>
</>
);
}
export default Navbar;
When I click the highlighted button the data in console shows undefined.
The event passed to handleSubmit is the click event on the button, so e.target.value is the value of the button, which is presumably undefined.
The quickest fix is to give the input an Id and select its value to pass to setSearchBarText:
const searchInput = document.getElementById("searchInput");
setSearchBarText(searchInput.value);
A "better" fix is to use state. Bind a handler to the input's onChange or onInput that updates a state value. Then you can bind a single submit handler to both the button's onClick and the input's onKeyDown that retrieves the state value and passes it to setSearchBarText()

(Using React) Why is the submit button when onClick is performed using onChange events and resulting in empty string? (useState question)

Description:
The submit button calls a function called displayFields. This function then console logs the state of the input fields. The start of the input fields is listened to by onChange that sets the new state.
Before clicking the submit button the input fields when something is entered console logs the current state of the fields and then provides each string character in the console. To my understanding onChange should listen for changes but not console anything. When the button is clicked it should perform the function one time and console the current state of what is entered in fields. Instead when clicked the fields clear and then console an empty string.
I will provide my code and screen shots to help.
const GetQuote = (props) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [question, setQuestion] = useState("");
const dispFields = () => {
console.log(name + email + question);
};
/*
This is used in case prevent defualt needs used
function handleSubmit(e) {
e.preventDefault(); }
*/
return (
<React.Fragment>
<form
id="quoteForm"
//onSubmit={handleSubmit}
>
<h1 id="quoteTitle"> Quote Help Form </h1>
<p id="quotePar">
{" "}
Please provide your Name, Contact Email, and what products you would
like more information about in this form:{" "}
</p>
<label id="formName" className="Form">
Name:
<input
type="text"
name="name"
onChange={(event) => {
setName(event.target.value);
}}
/>
</label>
<label id="formEmail" className="Form">
Email:
<input
type="text"
name="email"
onChange={(event) => {
setEmail(event.target.value);
}}
/>
</label>
<br />
<label id="formQuestion" className="Form">
What products would you like to know more about:
<input
type="text"
name="help"
onChange={(event) => {
setQuestion(event.target.value);
}}
/>{" "}
</label>
<br />
<br />
<button
id="quoteSubmit"
type="submit"
//funtion is called however seems to constantly call the useState which is used in onchange
//when submit is done returns empty string
onClick={dispFields()}
>
Submit{" "}
</button>
</form>
</React.Fragment>
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
onClick={dispFields()} is getting called on every render. If you pass it without calling it (onClick={dispFields} that should only log it to the console when the button is clicked.
You try to alter from
<
button id = "quoteSubmit"
type = "submit"
//funtion is called however seems to constantly call the useState which is used in onchange
//when submit is done returns empty string
onClick = {
dispFields()
} >
Submit < /button>
to
<
button id = "quoteSubmit"
type = "button"
//funtion is called however seems to constantly call the useState which is used in onchange
//when submit is done returns empty string
onClick = {()=>
dispFields()
} >
Submit < /button>
Changed "button" from "submit", arrow function involved
Both solutions provided above work. Changing to example = {example} from example = {example()}. Also calling it from a arrow function also works. The issue is a node issue. What happens when the use breakpoints is set on the function, the values are console logged however after they are console logged the form refreshes and then the state refreshes so the console logs are never logged because the browser processes the value of event and clears the event at the same time. So as long as the values can be passed to the backend, the front end can remain clearing the value being rendered.

Why do i have to click this radio button twice to set it active in react

Below is my code for handling the onClick for a radio button that uses images as its label
function foo(props) {
let id = props.id
id = id.replace(/[0-9]/g, '');
return (
<React.Fragment>
<input type="radio" name="foo" id={props.id} value={props.id} onClick={()=>{props.handle(id)}}/>
<label for={props.id}>
<Image src={props.src} style={foo} className="zoom" rounded />
</label>
</React.Fragment>
);
This is the code handling the state change for it
const [foo,setFooState] = useState("foo")
function updateState(e){
setFooState(e)
}
I am currently having an issue where I have to click the image twice in order for the radio button to be set as active
So i have found the issue which is i am passing the state change 2 parent up and that is causing some unintended issue.

Reactjs - toggle switches not working when using local array

I have an update for anyone that is reading this....
I think I've found the issue - when you set a toggle switch to checked it's also set to READONLY. So I can't toggle the toggle switch now.
I have a toggle component of type checkbox in React.
products is a locally set array for testing purposes as this.props.products is empty for now.
Through testing, I've noticed that if I use:
selected={(products.indexOf(p) > -1)} the toggles stop working. They display correctly but I'm not able to toggle them. They do not appear disabled or are set to disabled in HTML element.
products=['ProdA', 'ProdB', 'ProdC];
customerProducts.forEach(p => {
content(): string[] {
const toggles = [];
if(isEnabled){
toggles.push(
<ToggleComponent
value={p}
selected={(products.indexOf(p) > -1)}
onChange={this.props.onChange}
disabled={false}
/>
);
}
render() {
{this.content()}
}
//TOGGLE COMPONENT
render() {
const {id, title, disabled, name, value, selected} = this.props;
return (
<div>
<fieldset>
<div className="form-structure">
<label className={!this.props.disabled ? 'checkbox-switch-label' : 'checkbox-switch-label checkbox-switch-label-disabled'}>
<input id={id} type="checkbox" checked={selected} className="checkbox-switch" role="Switch" disabled={disabled} name={name} value={value} onChange={this.validate} />
<span/>{title}
</label>
</div>
</fieldset>
</div>
)}
I can see there is an invalid Event Listener in my dev Tools: dispatchDiscreteEvent
The toggles are appearing, are not visibly disabled, (there is no disabled attribute in the html element), but clicking them does not toggle them on/off.
Am I supposed to be setting 'disabled' against a state value instead?
I already have an onChange function elsewhere for getting the values.

Resources