Home > Software design >  How to show the icons based on the click function in react js [duplicate]
How to show the icons based on the click function in react js [duplicate]

Time:09-23

This is one of the component

const [mic, setMic] = useState(false)

const micClick = () => {
  setMic(true)
 alert('micClicked',mic)
}

<VideoControls
   micClick={micClick}
/>

this is other component

 const VideoControls = ({ 
   micClick,
 }) => {

 return (
    <Card style={style} className={classes.root}>
      <Button>
        <MicIcon style={iconStyle} onClick={micClick} />
      </Button>
      <Button>
         <MicOffIcon style={iconStyle} onClick={micClick} />
    </Button>
  }

I want to show the MicIcon as a default whenever button is clicked i want to change it as MicOffIcon , but here i dont have any idea how to utilize it. please help me thanks in advance

CodePudding user response:

Since you have a mic state you can pass it down and then based on that state render whatever icon you feel like, as example:

const [mic, setMic] = useState(false)

const micClick = () => {
  setMic(true)
 alert('micClicked',mic)
}
<VideoControls
   micClick={micClick}
   mic={mic}
/>

and then inside your VideoControls component:

const VideoControls = ({ 
   micClick,
   mic
 }) => {

 return (
    <Card style={style} className={classes.root}>
      <Button>
         {mic ? 
        <MicIcon style={iconStyle} onClick={micClick} /> : 
        <YourOtherIcon/> }
      </Button>
      <Button>
         <MicOffIcon style={iconStyle} onClick={micClick} />
    </Button>
  }

<VideoControls
   micClick={micClick}
   mic={mic}
/>

CodePudding user response:

Pass mic as a prop to your VideoControls component. And set your icons according to the value of mic.

const [mic, setMic] = useState(false)

const micClick = () => {
  setMic(mic => !mic); // change the value of mic 
  alert('micClicked',!mic)
}

<VideoControls
   micClick={micClick}
   mic={mic}
/>

VideoControls Component

 const VideoControls = ({ 
   micClick, mic
 }) => {

 return (
    <Card style={style} className={classes.root}>
      {mic ? 
      <Button>
        <MicIcon style={iconStyle} onClick={micClick} />
      </Button>
       :
      <Button>
         <MicOffIcon style={iconStyle} onClick={micClick} />
      </Button>
     }
  }

CodePudding user response:

You could pass your mic state variable to the VideoControls component and display the relevant Icon based on its value:

<VideoControls
   micClick={micClick}
   mic={mic}
/>

and

 const VideoControls = ({ 
   micClick,
   mic
 }) => {

 return (
    <Card style={style} className={classes.root}>
      <Button>
        {mic ? 
          <MicIcon style={iconStyle} onClick={micClick} /> :
          <MicOffIcon style={iconStyle} onClick={micClick} />
        }
      </Button>
    </Card>
 );
  • Related