How to implement css when onClick event occur in Reactjs
In ReactJS, you can implement CSS changes on an onClick event by using state
to manage the CSS styles and then updating that state when the event occurs.
Here's a step-by-step guide:
1.Create a React component:
import React, { useState } from "react"; import "./CSSViaOnClick.css"; function CSSviaOnClick() { const [isClicked, setIsClicked] = useState(false); const handleClick = () => { // Update the state when the button is clicked www.hackingtruth.in setIsClicked(!isClicked); }; // Define CSS classes based on the state www.kumaratuljaiswal.in const buttonClass = isClicked ? "clicked" : "unclicked"; return ( <div> <div className="main-div"> <button onClick={handleClick} className={buttonClass}> Click me </button> </div> </div> ); } export default CSSviaOnClick;
1. First of all we are written and import the two pkg first one is
react and another one is css file.
2. In this example, we create a functional component App that uses the
useState hook to manage the isClicked state. Initially, it's set to false.
3. We define a handleClick function
that will be called when the button is clicked. Inside this function, we
update the isClicked state using setIsClicked, toggling it between true and
false with each click.
4. Based on the isClicked state, we
determine the CSS class to apply to the button. In this case, we have two CSS
classes: 'clicked' and 'unclicked', which you can define in your CSS or use
CSS-in-JS libraries like styled-components.
5. Finally, we
render the button with the onClick event handler and the appropriate CSS
class.
Implement CSS
.main-div { left: 50%; top: 50%; text-transform: translate(-50%, -50%); position: absolute; border: 1px solid black; padding: 2px 6px 2px 6px; border-radius: 20%; font-weight: bold; } .clicked { color: red; letter-spacing: 2px; } .unclicked { color: blue; }
Wheneven user click on button then event occur and css works.
Disclaimer
0 comments:
Post a Comment
For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.