Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

useState settoggle


Pierre Ortega
@4ever
1:46am
const Toggle = () => {
  const [isToggledOn, setToggle] = useState(false)
  const toggle = () => setToggle(!isToggledOn)
  return (
     <button onClick={toggle}>
        {isToggleOn ? 'ON' : 'OFF'}
      </button>
  )
}
Comment

react hook toggle state

// import React, { useState } from 'react';
const { useState } = React;

function App() {
  const [checked, setChecked] = useState(false);
  const toggleChecked = () => setChecked(value => !value);
  return (
    <input
      type="checkbox"
      checked={checked}
      onChange={toggleChecked}
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Comment

toggle hook react

import { useCallback, useState } from 'react';
// Usage
function App() {
    // Call the hook which returns, current value and the toggler function
    const [isTextChanged, setIsTextChanged] = useToggle();
    
    return (
        <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button>
    );
}
// Hook
// Parameter is the boolean, with default "false" value
const useToggle = (initialState = false) => {
    // Initialize the state
    const [state, setState] = useState(initialState);
    
    // Define and memorize toggler function in case we pass down the component,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback(() => setState(state => !state), []);
    
    return [state, toggle]
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: angular access form control value 
Javascript :: javascript reduce array of objects 
Javascript :: httpclientmodule is not an angular module 
Javascript :: f string javascript 
Javascript :: js sort 1 or -1 
Javascript :: express send 401 response 
Javascript :: electron no menu bar 
Javascript :: javascript ascending and descending 
Javascript :: web-vitals react 
Javascript :: javascript string unique characters 
Javascript :: jquery image change on hover 
Javascript :: js int to alphabet 
Javascript :: devtools failed to load sourcemap when debugging react native 
Javascript :: load +main.js with system.import 
Javascript :: async storage get item 
Javascript :: javascript access php variable 
Javascript :: redux saga delay 
Javascript :: this is a problem related to network connectivity npm 
Javascript :: javascript get 24 hour time 
Javascript :: socket io client 
Javascript :: js matrix 
Javascript :: how to check checked checkbox in jquery 
Javascript :: replace array element javascript 
Javascript :: react form reload page 
Javascript :: download text file javascript 
Javascript :: convert base64 to image nodejs 
Javascript :: add month date now javascript 
Javascript :: object exists in array javascript 
Javascript :: read json from file js 
Javascript :: javascript if input number empty then make 0 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =