Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
How to access the state of a component at a superior level without using useContext?

let me explain my question. I would like to create expanding flex cards, here is the exemple on codepen : https://codepen.io/z-/pen/OBPJKK

and here is my code for each button : basically I have a component which is called HomeButtons that generates every flex cards. Inside this component I have a smaller component called readMore. In this component I have a useState that allows me to toggle individually each button to add or retreive an active class. If the active class is present, that means that the selected button must expand and the other ones must shrink.

What I would like to do is to access the readMore state ouside of the readMore subcomponent. That way I could write a function to remove the active class from a card if the user clicks on another card like so :

function setToUnactive() {
if (readMore(true)) {
readMore(false)}
}

My question is how can I get the state of readMore outside of the readMore subcomponent ? Do I need to use useContext ? Because that seems very simple to do but I tried a lot of things and nothing works. Can I pass the state readMore as a prop of the component ReadMore ? Thank you !

import React, { useState } from 'react';
import '../style/catalogue.scss';
import collectionsItems from '../Components/collectionsItemsData';
import { Link } from "react-router-dom";


const HomeButtons = ({}) => {

    function ReadMore() {
        const [readMore, setReadMore] = useState(false)
        function toggleSetReadMore() {
            setReadMore(!readMore)
        }
        return (
            <p className='showmore' onClick={toggleSetReadMore} className={readMore ? "collection-item active" : "collection-item"}>TOGGLE BUTTON</p>
        )
    }

    return <div>
        {collectionsItems.map((collectionItem) => {
            const { id, category, img } = collectionItem;
            return < article key={id} >
                <img className="item-img" src={img} alt=''/>
                <ReadMore />
                <Link to={`/${category}`} className="item-title">{category}</Link>
            </article>
        })}
    </div>
}

export default HomeButtons;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First of all you need extract ReadMore component from function outside! And for your problem you can lift state up(https://reactjs.org/docs/lifting-state-up.html). And since at the same time only one item can be opened you can do something like this:

function ReadMore({ isOpened, setOpened }) {
  return (
    <p
      onClick={setOpened}
      className={isOpened ? "collection-item active" : "collection-item"}
    >
      TOGGLE BUTTON
    </p>
  );
}

const HomeButtons = () => {
  const [openedItemId, setOpenedItemId] = useState(null);

  return (
    <div>
      {collectionsItems.map((collectionItem) => {
        const { id, category, img } = collectionItem;
        return (
          <article key={id}>
            <img className="item-img" src={img} alt="" />
            <ReadMore
              isOpened={openedItemId === id}
              setOpened={() => setOpenedItemId(id)}
            />
            <Link to={`/${category}`} className="item-title">
              {category}
            </Link>
          </article>
        );
      })}
    </div>
  );
};

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda