Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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 :: sh: /Users/ahmedqadri/Desktop/Projects/stockNotesAPP-frontend/node_modules/.bin/react-scripts: Permission denied 
Javascript :: javascript get device width 
Javascript :: javascript array add 
Javascript :: picker change event react native 
Javascript :: dynamic import javascript 
Javascript :: difference between statement and expression 
Javascript :: sortby vue 
Javascript :: javascript loop an array 
Javascript :: time taken for a function javascript 
Javascript :: bulk create in sequelize 
Javascript :: javascript list include 
Javascript :: async await mongoose connection 
Javascript :: javascript wait for dom 
Javascript :: javascript prime number 
Javascript :: javascript how to check if array is empty 
Javascript :: add multiple event listeners 
Javascript :: get unique array javascript 
Javascript :: javascript get element by id 
Javascript :: jquery add event after page load 
Javascript :: react and react dom cdn 
Javascript :: js date enlever jour 
Javascript :: [PrivateRoute] is not a <Route component. All component children of <Routes must be a <Route or <React.Fragment 
Javascript :: add parameter to url without reload jquery 
Javascript :: getcomputedstyle 
Javascript :: ajax upload image 
Javascript :: how to send query parameters in url vuejs 
Javascript :: add formdata javascript 
Javascript :: how to read breakline in html 
Javascript :: foreach db mongodb 
Javascript :: http to https express js 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =