user9855821
user9855821

Reputation:

Toggle arrow issue react hooks

can you help me with the following issue: I have a react Hooks component and I want to toggle arrow when I click on the span, it works but only once, when I click it again it doesn't work no more, I don't understand why? Here is my component:

const ViewDetails = () => {
  const [ expanded, setIsExpanded ] = useState(false)

  const info = expanded ? 'Hide details' : 'View details';

  return (
  <div className={styles.viewDetails}>
    <span 
    className={ expanded ? styles.expanded : undefined }
    onClick={() => !setIsExpanded(true)}
    >
      <DownArrow />
    </span>
  <span className={styles.viewDetails}>{info}</span>
  </div>
  )};

Upvotes: 0

Views: 484

Answers (2)

subashMahapatra
subashMahapatra

Reputation: 6837

You can use the previous state value to toggle expanded. The current function {() => !setIsExpanded(true)} will return true for all cases.

The solution.

const toggle = () => setIsExpanded((val) => !val);

return (
  <div className={styles.viewDetails}>
    <span 
    className={ expanded ? styles.expanded : undefined }
    onClick={toggle}
    >
      <DownArrow />
    </span>
  <span className={styles.viewDetails}>{info}</span>
  </div>
  )};

Codesandbox example -- codesandbox

Upvotes: 1

Toby Djelyinski
Toby Djelyinski

Reputation: 138

in the span onClick, try writing:

onClick={() => setIsExpanded(!expanded)}

Upvotes: 0

Related Questions