Is there a way to ensure that only one button is the focus at a time, rather than multiple buttons being focused simultaneously?

Can you assist me with styling? I am having an issue where only one of my buttons can turn blue (focus) at a time, instead of multiple buttons turning blue simultaneously.

This is how my components are structured...

import { Container, Content } from './styles';

function PressedButton({ children, ...rest }) {
  const [pressed, setPressed] = useState(false);

  return (
    <Container>
      <Content
        type="button" {...rest}
        pressed={pressed}
        onFocus={() => setPressed(!pressed)}
        >
      {children}
      </Content>
    </Container>
  );
}

The styles for the PressedButton component are as follows...

import styled from 'styled-components';
(...)
export const Content = styled.button`
  (...)

  //props
  background: ${({ pressed }) => pressed ? `linear-gradient(#449fd8, #1b699a)` : '#2a2a2a'};
  color: ${({ pressed }) => pressed ? '#fff' : '#7d7d7d'};

Here is a visual representation of my problem

In my parent component, the rendering looks like this...

tags.forEach((tag) => {
    let output = <PressedButton onClick={() => handleTag(tag)}>{tag}</PressedButton>

Answer №1

To achieve the desired outcome, consider structuring your code like this:

function parentComponent() {
  // vvv new line added here vvv
  const [pressedIndex, setPressedIndex] = useState(null);
  // ... rest of the code
  // vvv additional code compared to your original implementation vvv
  tags.forEach((tag, index) => {
    let output = <PressedButton pressed={pressedIndex === index} onClick={() => {handleTag(tag); setPressedIndex(index)}}>{tag}</PressedButton>
}

In the child component:

function PressedButton({ children, pressed, ...rest }) {
  // vvv removed line vvv
  // const [pressed, setPressed] = useState(false);

  return (
    <Container>
      <Content
        type="button" {...rest}
        pressed={pressed}
        onFocus={() => setPressed(!pressed)}
        >
      {children}
      </Content>
    </Container>
  );
}

This approach involves lifting the state up to the parent component. Following React's state management principles, if a piece of state needs to be shared among buttons, it should reside in the component responsible for rendering those buttons.

Answer №2

Here is a suggestion I have: check out this codesandbox

The concept involves storing the button's identification in the state and adding or removing the ID on click events.

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

Is there a way to invoke a function from a component that is neither a direct child nor parent component?

Module X let searchQuery = .... retrieveData(searchQuery); Module Y //implementing the use of Module X's parameter ...

Safari's approach to image height measurement

I am experiencing an issue with some images in Safari. While they display correctly on other browsers, the images are appearing too high on Safari. You can view the website at development.mar-bakker.nl <div class="col-xs-12 col-sm-4 col-md-4"> ...

Tips on modifying the style of a specific React component without affecting the others

In my attempt to modify a single style property of a specific React component upon clicking it, I encountered an issue where the changes applied to every instance of that component. Despite consulting the React tutorial and various sources for solutions, I ...

javascript containing the response message

I've created an Ajax function that retrieves a script from the server containing RSS feed information. I'm currently placing this response within a div using: $("#divId").html(responsetext); My goal is to execute the script included in the resp ...

Errors occurred when trying to use Jquery to handle a JSON response

enter code here function customPaging(action, action1, page) { alert("in customPaging"); $.getJSON("./paging.do?action="+escape(action)+"&p="+escape(action1)+"&str="+escape(page), function(data){ alert("Length: "+data.length); var options = ...

inject spinner during the call and verify status post-call

How can I make the loading icon display during the save function call and then switch to the check mark icon after the function resolves instead of mocking it on a timeout? function save() { successMessage() new Promise((resolve, reject) => { setTim ...

Using Flask to trigger a Python function that requires input parameters when a button is clicked

I am working on a Flask web application that includes a download button. Instead of triggering a JavaScript function, I want the button to execute a Python method. This Python method should take the recently modified HTML code from the webpage as input. H ...

Issue with CoffeeScript and three.js: scene not defined

I've been troubleshooting this issue for hours, but I can't seem to figure out the error... Here's the error message I'm getting: Cannot read property 'add' of undefined Below is my coffeescript code file (hopefully it&apos ...

I'm having trouble with my JavaScript function when it is called simultaneously by two different sources

In this scenario, two calls to the function are made simultaneously. First call: triggered by setInterval, skips the animation, Second call: executed after $(document).ready and performs correctly. fadeInFadeOut : function (oldContent, newContent, flag) ...

Utilize API information to populate a dynamic selection dropdown menu

Objective: Utilize an API to fetch data and then implement it in a dynamic select dropdown menu. The value should be set as the id and the label should be displayed as the name. Issue: How can you retrieve and incorporate the data into the select dr ...

Concealing a Vuejs dropdown when clicking outside of the component

I am currently working on a Vuejs project where I am creating a menu component. This menu consists of 2 dropdowns, and I have already implemented some methods and used Vue directives to ensure that when one dropdown is clicked, the other hides and vice ver ...

Include a Custom Button with an Optional Event Handler

I've created a customized material-ui button component: type ButtonProps = { disabled: boolean; text: string }; export function CustomButton({ disabled, text }: ButtonProps) { return ( <Button type="submit" disabled={disabled} ...

`Place text to the right side of the image`

Is there a way to align all three lines of text to the right of an image without wrapping on the second line? If you have any suggestions, please let me know! Check out this JSFiddle for reference. CSS: img { min-width:75px; height:90px; ve ...

The character is having trouble displaying correctly in the ajax response

I've been searching for solutions but nothing seems to help. The issue I'm facing is with reading characters from an AJAX response. How can I properly read characters that are coming from an AJAX response in the form of a JSON object? ["label" ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

An Exploration into the Error Situations of NPM Request Library

I'm encountering an issue with the callback in my request function. I'm trying to figure out the specific circumstances under which an error is passed to this callback. const req = require('request'); req('http://www.google.com&ap ...

Use Django, Ajax, and Jquery to incrementally add items to a "cart" by selecting checkboxes one by one

Despite adding new code, it's still not working as expected... I've been attempting to implement a feature where users can select items using checkboxes and add them to the "cart" displayed at the top of the page. Each item on the page has a che ...

What is the process of converting a default export to a named export?

Take a look at the following code snippet: const MyComponent = props => <div>Hello</div> export default React.memo(MyComponent) In this code, React.memo(MyComponent) is being exported as default. Is there a way to export it as a named expor ...

The parameter necessary for [Route: admin.request.update] is missing. The required URI is admin/request/{request}, and the missing parameter is 'request'

When attempting to access detail.blade.php, I encountered an error stating "Missing required parameter for [Route: admin.request.update] [URI: admin/request/{request}] [Missing parameter: request]." Despite following the steps and codes exactly as in my pr ...

Is there a solution for overflow indicators in combination with a FlexBox column layout?

To clarify this question, we do not have to provide a CSS-only solution. We are open to using JavaScript in our data-driven project. Hello! Thank you for visiting. In summary, we want to enhance Flexbox column layout by breaking the content at specific ...