Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
I want to change display of a div when clicked -React Styled Component

I am creating a div using styled component. I want to change the visibility of the div on button clicked,

const Category = () => {
  const [showCategory, setShowCategory] = useState(false)


  useEffect(() => {
    setShowCategory(false)
  }, [])
  return (
<button onClick={() => {  setShowCategory(true)}}>
   New Category
</button>
        <AdminInputStyle>
          <form>
            <form-group>
              <label>Add Category</label>
              <input type='text' />
            </form-group>
            <button>Submit</button>
          </form>
        </AdminInputStyle>

  )

}

Here's the styled component

const AdminInputStyle = styled.div`
  display: ${(d) => (d.showCategory ? 'show' : 'hidden')};
`
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I have an example, but in the case we will use a Button. Clicking it will alter the visibility.

  1. You must pass a property to the styled component if you want it to be visible based on that prop. In your example, you don't pass a prop to the styled component in this scenario, which is why the component cannot detect if it should be visible or not.

  2. You will need to / can use the css function from the styled-components library. This can help you return styles based on the properties your styled-component will have. In this example, our property that we pass to the button will be called visible.

import React from 'react';
import PropTypes from 'prop-types';
import styled, { css } from 'styled-components/macro';

const StyledButton = styled.button`
    border-radius: 3px;
    color: white;
    background-color: green;
    cursor: pointer;
    width: 100px;
    height: 50px;

    ${({ visible }) => {
        return css`
            visibility: ${visible ? 'visible' : 'hidden'};
        `;
    }}
`;

export default function Button({ children, visible, onClick }) {
    return (
        <StyledButton visible={visible} onClick={onClick}>
            {children}
        </StyledButton>
    );
}

Button.propTypes = {
    children: PropTypes.node,
    visible: PropTypes.bool,
    onClick: PropTypes.func,
};

You can see that passing the visible prop will enable the button to alter its' styles based on whether that property is true or false. We utilize a function within the component that returns the css function and this will control the visibility css property.

Here is how we utilize the button and pass props to it from another component; in this example just the App.js file:

import React, { useState } from 'react';
import './App.css';
import Button from './components/Button';

function App() {
  const [visible, setVisible] = useState(true);

  function handleClick() {
    setVisible(!visible);
  }

  return (
    <div className="App">
      <Button visible={visible} onClick={handleClick}>
        Click
      </Button>
    </div>
  );
}

export default App;

FYI: For the css; you don't want display: hidden;. hidden is an invalid value for the display prop. You'd want display: none; if you don't want the element to be in the DOM. visibility: hidden; will add the element to the DOM, but it won't be visible. You can use whichever works best for your case 👍🏿

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try something like this too, show when you need to show the add category when you press add category

return (
    <>
      <button
        onClick={() => {
          setShowCategory(true);
        }}
      >
        New Category
      </button>
      {showCategory && (
        <AdminInputStyle>
          <form>
            <form-group>
              <label>Add Category</label>
              <input type="text" />
            </form-group>
            <button>Submit</button>
          </form>
        </AdminInputStyle>
      )}
    </>
  );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda