Implementing a color change for icons in React upon onClick event

export default function Post({post}) {

const [like,setLike] = useState(post.like)
const [islike,setIslike] = useState(false)

const handler=()=>{
setLike(islike? like-1:like+1 )
setIslike(!islike)

}
return (
<>
<div className="postcontainer">
   <div className='postwrapper'>

    <div className="postTop">
        <div className="topleft">
            <img className="images" src= {Users.filter((u)=> u.id === post.userId)[0].imagesProfile} alt="profile" />
            <span className="names"> {Users.filter((u)=> u.id === post.userId)[0].userName} </span>
            <span className="dates"> {post.date}</span>

        </div>
        <div className="topzRight">
        <MoreVert />
        </div>

    </div>
    <div className="postcenter">

       <span className='text'>{post.descrip}</span>
       <img className="imagepost" src={post.imagesPost} alt="newpost" />

    </div>
    <div className="postbotton">
        <div className="postbottonLeft">
        <LocationOnIcon     className="icon" />
        <FavoriteIcon   className="icon" onClick={handler}/>
       
        <span className='counter' > {like} People liked it</span>
        </div>
        <div className="postbottonRight">
        <span>{post.comment} comments</span>
        <SmsOutlined className="iconcomment" />
        </div>

    </div>
    </div> 
</div>
</>;
)

Answer №1

To start, it's important to communicate your intentions in the code rather than solely relying on the title to convey your question and using the body for the code.

Additionally, if you're looking to change the color of an HTML element based on whether it has been clicked or not, consider creating CSS classes for each desired state. For example, you could have a class called .isLiked and another called .isNotLiked, each representing a different color. Then, within your code, use a conditional statement on the className attribute of the HTML element to determine which class should be applied based on a condition.

For instance:

className={isLiked ? 'isLiked' : 'isNotLiked'}

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

Are extra parameters in the URL causing issues with AngularJS routing?

When I receive password reset instructions in my app, the URL I use to go to the server looks like this: /changepass?key=1231231231212312 In the controller, I have the following code: if (typeof $routeParams.key !== 'undefined') { $scope ...

Ways to stop Bootstrap 4 dropdown from appearing when clicking on an input field?

Here is a straightforward bootstrap dropdown menu example, but with a twist - the toggle element is a text input. Instead of showing the dropdown on click event, I want it to appear when the user inputs something so I can dynamically populate the menu base ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...

Error: The server instance pool has been terminated, requiring enhancements to the existing solution

I'm facing an issue where removing the client.close() seems to solve the problem, but I can't leave connections open to the database after the function is done. It doesn't feel secure to me. Even though the initial write completes successful ...

What could be causing the MIME type error in my Django/React app when trying to load CSS/JS files from AWS?

Recently, I successfully deployed a Django-Rest/React app on Heroku and utilized AWS S3 buckets to host my static and media files. Upon accessing the API URL or admin URL, everything worked smoothly. However, when attempting to access my React URLs, I enco ...

Updating row values in an Angular table

I have a reusable table with the [cellData]="row" attribute to populate each cell on the table (see sample table in the screenshot). My question is, how can we replace the null values on the template with "---" so that instead of displ ...

When attempting to install React Native on a Mac using the "npx react-native init MyTestApp" command, the

PROBLEM I am encountering difficulties while attempting to install and execute the react native todo command - npx react-native init MyTestApp on my MacBook Pro. The specific challenges I am facing are: The detailed github issue can be found here: here ...

Send the data from a div to a different page using PHP

Is there a way to pass the value displayed in DIV id to another page? The data is retrieved from another page and shown within the given code. <div id="res" style="float: left; Padding-left: 3px; padding-right:13px;line-height: 15px;"> ...... ...

Pass data in JSON format from Laravel controller to AngularJS

When working with Laravel, I successfully converted data in MySQL to JSON for use in AngularJS. However, I am now unsure of how to effectively utilize these values in AngularJS. Can anyone offer assistance? View output data (hide each value) Controller ...

Tips for maintaining a sticky header while continuing to utilize Bootstrap table classes such as table-responsive and table-stripped

This is Here's my code on jsfiddle I've attempted to make the header sticky while maintaining the current layout, but every approach I've tried ends up messing with the responsiveness of the table. My next plan involves using a JavaScript ...

Is there a way to select and handle multiple elements using async wdio with the same selector?

My test scenario involves using async wdio to test my React app, where I need to count elements with a specific selector and check their contents. The code snippet being tested is as follows: <div className='container'> <li className= ...

Leveraging ASP.NET MVC 5 to integrate an online document viewer from Office 365, seamlessly displaying Word documents within a sleek, compact window

We have been struggling to showcase a Word document (.docx) within an iframe on our website using the Office 365 service. The document is stored in One-Drive for business online and has been appropriately shared. After signing in, we obtained a link to the ...

How can you align two div elements side by side, if the first div is spanning across two lines?

I'm looking to position two divs next to each other, with the second div starting right where the first one ends. I came across a similar question on Stack Overflow, but unfortunately, it didn't have the answer I needed. <div id="wrapper"> ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Understanding the functionality of scope in AngularJS is essential for mastering the framework

Why does this code work? app.controller("ctrl", function($scope){ $scope.From = "Santa"; $scope.To = "Claus"; }); And why doesn't this one work? app.controller("ctrl", function(scope){ scope.From = "Santa"; scope.To = "Claus"; }); ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

The fetch() function is inundating my API with an overwhelming amount of requests

After implementing the following function to retrieve images from my API, I encountered an issue: function getImages() { console.log("Ignite"); fetch('https://api.itseternal.net/eternal/stats', { headers: { & ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

The error "ReferenceError: window is not defined" occurs when calling client.join() due to

I am looking to create a video call application using React and Next.js with the AgoraRTC SDK. After successfully running AgoraRTC.createClient(), AgoraRTC.createStream(), and client.init(), I encountered an error when trying to execute client.join(). The ...