Adjust the appearance depending on the React state variable

I am trying to add animation to a search icon when clicked in React. Using the useRef hook, I am able to access the element and applying custom styles to it.

const [searchBar, setSearchBar ] = useState(false);
const searchIcon = useRef();
const searchIconStyle = {
    transition: 'rotate .3s ease', // smooth transition
    rotate: searchBar? "360deg" : "0",
}

function handleSearchClick(e) {
    setSearchBar(prevState => !prevState);
}

The above code works as expected the first time I click, but subsequent clicks do not trigger the animation. The search icon is created using FontAwesome components

 {searchBar && <input type="search" placeholder="Search product..."/>}
        <FontAwesomeIcon icon={faMagnifyingGlass} className="search-icon"
            onClick={handleSearchClick} ref={searchIcon} style={searchIconStyle}/>

I would like to animate the icon with each click based on changes in the searchBar variable. How can this be achieved?

Answer №1

Ensure you are correctly setting the rotate property.

Simply update to:

rotate: searchBar? "360deg" : "0deg",

Change it from:

 rotate: searchBar? "360deg" : "0",

This example is demonstrated in codesandbox (I used a button instead of FontAwesomeIcon since the library being used was not specified)

Answer №2

I enjoy utilizing class names in my code. Here's an example for you:

className={classNames(
  { 'basicStyle': true},
  { 'withoutAnimation': !searchBar },
  { 'withAnimation': searchBar },
)}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving Center Alignment for Material-UI's <Table> within a <div> using ReactJS

Currently, I am working with a Material-UI's <Table> embedded within a <div>. My goal is to center the <Table> while maintaining a fixed width. I want the table to remain centered in the browser, but if the browser window is minimize ...

Notes should be added to the Flutter page when it is executed on the emulator

I am working with 2 widgets in my project: ProjectPage and ProjectPageWeb, both of which have similar functionalities in displaying an iframe. The difference lies in the fact that they use different components to achieve this. ProjectPage utilizes the Web ...

Building a Gatsby website with a PHP contact form

Currently, I am developing a Gatsby portfolio and my goal is to integrate a PHP contact form. While exploring various examples online, many of them suggest using external resources to handle email sending directly from the website itself. One such recommen ...

Trying to align a Material UI button to the right within a grid item

I'm attempting to right float the button below using material-ui, but I'm unsure of how to achieve this: <Grid item xs={2}> <Button variant="contained" color="secondary&quo ...

What is the best way to directly serve a static html file from a server using React and Express?

I recently downloaded a visually appealing HTML page with links to necessary CSS and JS files from a website builder. My intention is to use this page as the landing page for my React application. However, I'm unsure of the best approach to achieve th ...

The issue of importing CSS files that themselves import other CSS files via URL is causing a problem

Why is this not working correctly? I have included [email protected] A.css (css file that imports from a URL) @import url('https://fonts.googleapis.com/css?family=Source Sans Pro:300,400,600,700,400italic,700italic&subset=latin'); Ap ...

Tips for solving issues with dependencies in React applications

After running "npm install," I encountered the following errors in the console: elena@elena-dev:~/PROYECTO FINAL CTD/grupo-12/frontend/proyecto-integrador$ npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While reso ...

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

Troubleshooting problem with displaying HTML content on Internet Explorer 10

My website was developed using jquery with a dynamic coding style. It was functioning properly in IE10 while working from Visual Studio. However, after deploying it to the production server, the entire style seemed broken in IE10. In all other versions o ...

Would it be beneficial to assign a single class name to all elements with matching styles within a CSS framework?

Currently, I am in the process of creating my own CSS library or framework. However, I have encountered an issue where all 10 li tags share the same classes, such as .pl{ padding-left:10px} .mr{ margin-right:10px}, along with other necessary attributes. Wh ...

The act of sending back Null from the Array.map() function

I've been attempting to retrieve data from a JavaScript object using the array.map() function. However, the result I'm receiving is null. I'm confused as to what the issue might be. Here's the object: export const Course = [ { co ...

Adjusting the rotation transform by deleting and reapplying canvas is causing the chart to not display data after redrawing

I am facing a challenge with my previous issue and I am exploring different solutions. One approach I am considering is to remove the canvas element completely and then re-add it, effectively resetting all rotations on the canvas. Although this method alm ...

Minimal - Combining a module with a parent component

To provide some background, I am utilizing bootstrap nav pills as triggers for bootstrap collapsibles. This is a simplified representation of the LESS code for bootstraps nav pills: .nav-pills { > li { // Active state &.active > a ...

Encountered a MySQL error while attempting to insert an image into the database

I have a task to work on a website where users can upload product images that will be stored in a MySQL database. The code for my HTML form is: <FORM action="testimage1.php" ENCTYPE="multipart/form-data" method="post"> <div st ...

Scrollable tabs with FlatLists inside a ScrollView, reminiscent of the layout found on popular social media profile

I am seeking to implement a set of tabs, each containing a FlatList within a ScrollView, similar to the layout seen on Instagram or Twitter. However, I have encountered challenges with having a FlatList within a ScrollView and triggering the onEndReached ...

Issue with passing props to child component in React due to TypeScript error

In the process of developing an expense tracker app using react and typescript. expense_type.ts export type IState = { id : number, text : string, amount : number } export type IinitialStateType = { transactions : IState[] } expor ...

I'm having trouble getting NextJS dynamic routes to function properly on my local server

src/app/user/[username].js [username].js content: import { useRouter } from 'next/router' export default function User() { const router = useRouter() return ( <p> {router.query.username} </p> ); } Upon visiting ...

What is the best way to access form data in an AWS Lambda function coded in NodeJs?

In the process of constructing an application, I am utilizing ReactJS for the front-end and AWS API Gateway/AWS Lambda in NodeJS for the back-end. The form data from my React app is being passed within the userAttributes attribute as illustrated below: ht ...

Error in Typescript: The data type 'string | undefined' does not meet the requirements of 'string | number | symbol' constraint

Working with typescript and react. Trying to dynamically adjust font size based on props (xs, sm, md, lg). Attempted using Record but encountering a typescript error. Error message: Type 'string | undefined' does not satisfy the constraint & ...

increasing the size of the drop-down menu width

I have been struggling to adjust the width of my dropdown list box on my page. Despite my efforts, I cannot seem to make it bigger. Here is the code snippet causing me trouble: <div class="form-group row"> <div class="col-sm-1&quo ...