Search code examples
reactjstypescriptonclickdom-eventsstyled-components

How to modify DOM in React - typescript - Styled-components app with click event?


i have an app built by React, Typescript and styled components (beginner with typescript and styled components). i want to create a simple click event that switches between which of the two child component is visible inside parent component. could you please help me fix my code or suggest an alternative way?

here is a code of what i had in mind with the parts i cannot solve in //comment:

let flipSwitch: boolean = false;

export const myCard: React.FC<myProps> = (props) => {
  return (
    <Parent onClick={e => {
       if (!flipSwitch) {
         // dontn't know how to write this part:
         //e.get Child1 element.style.display = 'none';
         //e.get Child2 element.style.display = 'none';
         flipSwitch = true;
        } else {
         //e.get Child2 element.style.display = 'none';
         //e.get Child1 element.style.display = 'block';
         flipSwitch = false;
       }
     }
      
    }>
      
      <Child1>
          <GrandChild>{props.whatever}</GrandChild>
          <GrandChild2>{props.whatever}</GrandChild2>
      </Child1>

      <Child2>
          <GrandChild3>{props.whatever}</GrandChild3>
          <GrandChild4>{props.whatever}</GrandChild4>
      </Child2>

    </Parent>
  )
}

Solution

  • You can use state and conditional state on the component itself:

    import React, { useState } from 'react';
    
    export const myCard: React.FC<myProps> = (props) => {
      const [flipSwitch, setFlipSwitch] = useState(false)
    
      return (
        <Parent onClick={e => setFlipSwitch(!flipSwitch)}>
          
         {flipSwitch &&
           <Child1>
              <GrandChild>{props.whatever}</GrandChild>
              <GrandChild2>{props.whatever}</GrandChild2>
           </Child1>
         }
    
        {!flipSwitch &&
          <Child2>
              <GrandChild3>{props.whatever}</GrandChild3>
              <GrandChild4>{props.whatever}</GrandChild4>
          </Child2>
        }
    
        </Parent>
      )
    }
    

    I don't really know which one should show on your code, but just play around with that ^^