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