Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this -

const MyComponent = () => (
    <ContainerSection>
        <DeleteButtonContainer>
            <Button
                theme="plain"
                autoWidth
                onClick={() => {
                    onDeleteClick();
                }}
            >
                Delete
            </Button>
        </DeleteButtonContainer>
    </ContainerSection>
);

I am trying to display the DeleteButtonContainer only when the user hovers over the ContainerSection. Both are implemented as styled-components. Although I searched for ways to achieve this using just CSS (utilizing the hover state of the parent within the child), I could not find a solution. As an alternative, I added a state like so -

const MyComponent = ()=>{
    const [isHoveredState, setHoveredState] = useState<boolean>(false);
    return (<ContainerSection onMouseEnter={() => setHoveredState(true)} onMouseLeave={() => setHoveredState(false)}>
        <DeleteButtonContainer style={{ display: isHoveredState ? 'block' : 'none' }}>
            <Button
                theme="plain"
                autoWidth
                disabled={!isHoveredState}
                onClick={() => {
                    onDeleteClick();
                }}
            >
                Delete
            </Button>
        </DeleteButtonContainer>
    </ContainerSection>)
};

Now, my goal is to have the DeleteButtonContainer always visible on mobile devices where hovering may not be possible. While additional JavaScript can address this, I prefer a CSS-based solution and ideally would like to eliminate the need for state entirely.

Is there a way to accomplish this using styled components without custom JS?

Answer №1

Including one component inside another is possible, and media queries can be used to activate the styling for larger screens.

Try hovering over the golden bar to reveal the button, and then reduce the width to deactivate the hover effect.

const DeleteButtonContainer = styled.div``;

const ContainerSection = styled.div`
  height: 2em;
  background: gold;
  
  @media (min-width: 640px) { // apply style when screen is wider than 640px
    &:not(:hover) ${DeleteButtonContainer} { // hide DeleteButtonContainer if it's not hovered inside a ContainerSection
      display: none;
    }
  }
`;

const Button = styled.button``;

const MyComponent = () => (
<ContainerSection>
  <DeleteButtonContainer>
    <Button>
      Delete
    </Button>
  </DeleteButtonContainer>
</ContainerSection>
);

ReactDOM.render(
  <MyComponent />,
  root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.0/styled-components.js"></script>

<div id="root"></div>

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

Using a Custom Material-ui button in a React application for repeated use

I am currently working on my first React application. I have successfully imported a Material-ui button and customized it to my liking. Now, I would like to use this custom button in multiple components within my app, each time with different text. Where ...

No information available, skipping Antd Table page

Utilizing an offset-based paginated GraphQL endpoint, the fetched data is presented within an Antd Table. While navigating through the pages functions appropriately, with new data being retrieved and appended to existing data, skipping a page triggers the ...

How come AngularJS $onChanges isn't able to detect the modification in the array?

What is the reason behind Angular's failure to detect changes in an array, but successfully does so after changing it to null first? In my AngularJS component, I utilize a two-way data binding to pass an array. The parent component contains a button ...

Why does my Redux callback keep getting invoked multiple times?

In developing a react application with redux, I have chosen to avoid using react-redux by manually handling all dispatched events. Below is a sample code snippet. The content of index.html <!DOCTYPE html> <html> <head> <script src=& ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

Experiencing Limitations with Node.JS node-hbase Scan Functionality, Unable to Retrieve More than 1000

I am facing an issue while trying to retrieve records from an HBase table in Node.JS using the node-hbase module, which connects to the rest server. I am able to fetch the first batch of records successfully, but I am struggling to get the next set of re ...

Viewing the details of a checkbox option

I have encountered a situation where I need to handle detail rows within a table that contain checkboxes for selection. The desired behavior is: 1) When clicking on the detail row image, it should expand to show the details of its parent row without sele ...

Issue with Material-ui autocomplete not updating its displayed value according to the value prop

My task involved creating multiple rows, each containing a searchable Autocomplete dropdown populated through an API, along with other fields. Everything was functioning perfectly until I encountered an issue when deleting a row from the middle. After dele ...

Unable to delete data in Laravel 8

I am new to Laravel and facing an issue when trying to delete a row with a modal. The problem is that only the first row is getting removed and I can't figure out the reason. Here is my modal setup: <p class="card-text"><small clas ...

Tracking a user's path while redirecting them through various pages

Recently, I created a website with a login page and a home page using nodejs, javascript, and html. The client side sends the entered username and password to the server, which then replies based on the validation result. During navigation between pages, h ...

Is there a way to fill the remaining height of the parent with the middle item when sandwiched between two others using CSS?

I am facing a design challenge with a parent container that has 3 children arranged vertically. The top and bottom children are wide (600x200), while the middle child is tall (200x600). The parent container itself is much smaller (100x200) as I want to ens ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

I'm looking to create a Triangle shape with CSS, any tips on how to achieve

Similar Question: Understanding the mystery behind this CSS triangle shape Please provide me with your valuable suggestions. ...

Changing the value of the static key boolean within a react-grid-layout's layout object results in a misalignment of all grid items

tl;dr: React-grid-layout has an issue where grid items are incorrectly moved around when the static option is toggled. I want the grid items to stay in place when static and only move when users interact with them while static mode is disabled. Check out ...

React JS issue with SVG linearGradient not displaying accurate values

Within my component, I am working with SVG paths and a linearGradient value passed down from the parent component through static data. The properties 'startColor' and 'stopColor' are used to define the gradient colors for each element. ...

ReactJS: The object's value is not defined

I am working on developing an application to display Covid 19 statistics. Initially, I aim to showcase global figures when the component is loaded using useEffect hooks. However, upon attempting to render global.confirmed, it returns an object. When I furt ...

Get the HTML source code for a form that has been created using AngularJS

Can AngularJS be used to download a portion of code generated by a form? Insert the following code snippet: http://jsbin.com/nufixiwali/edit?html,js,output I am looking to generate an .html file that only includes the code generated after the html tag. ...

Using Django Template Variables in JavaScript Functions

Within one of my templates, there is a for loop that iterates over all the items. Whenever a user likes or dislikes an item, it should trigger a function in my code. I successfully set up the button's HTML like this: <button onclick='update_li ...

Contrast between using 'let import React from "react/addons"' and 'import { PropTypes } from "react/addons"'

Can you explain the distinction between these two scenarios: import React from 'react/addons'; let {PropTypes} = React; versus import React, { PropTypes } from 'react/addons'; Should we adhere to a specific convention when importing ...

Adjust the CSS extension within the about:config settings of Firefox

I've been using the Zotero extension and I want to adjust how TinyMCE handles paragraph spacing. I'm looking to customize the CSS in extensions.zotero.note.css by adding specific CSS rules. The reason I want to make these changes is because I fe ...