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

209
Vistas
Toggle show/hide to a specific element

I have this particular code that shows a list of questions and buttons for each of it. When I click the button, it will show the specific answer to the question. My problem is, I have a bunch of questions and when i click the button, it will show all of the answer instead of the specific answer to that question.

Here is the code

class App extends React.Component {
 constructor(){
  super()
  this.state = {
                  answer: [],
                  isHidden: true
               }
  this.toggleHidden = this.toggleHidden.bind(this)
}

componentWillMount(){
  fetch('http://www.reddit.com/r/DrunkOrAKid/hot.json?sort=hot')
    .then(res => res.json())
    .then( (data) => {
      const answer = data.data.children.map(obj => obj.data);
      this.setState({answer});
     })
 }

toggleHidden(){
  this.setState({isHidden: !this.state.isHidden})
}

render(){
    const answer = this.state.answer.slice(2)
    return <div>
             <h1>Drunk or Kid</h1>
             {answer.map(answer =>
              <div key={answer.id}>
                <p className="title">{answer.title}</p>
                <button onClick={this.toggleHidden}>Answer</button>
                {!this.state.isHidden && <Show>{answer.selftext}</Show>}
               </div>
             )}
           </div>
  }
}
const Show = (props) => <p className="answer">{props.children}</p>

And here is the link to the codepen

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Here is a Codepen based on my suggestion:

The basics of the child component would be:

class Question extends React.Component {
  // Set initial state of isHidden to false
  constructor() {
    super();
    this.state = {
      isHidden: false
    }
  }
  // Toggle the visibility
  toggleHidden() {
    this.setState({
      isHidden: !this.state.isHidden
    });
  }
  // Render the component
  render() {
    const { answer } = this.props;
    return (
      <div key={answer.id}>
        <p className="title">{answer.title}</p>
        <button onClick={ () => this.toggleHidden() }>Answer</button>
        {this.state.isHidden && <Show>{answer.selftext}</Show>}
      </div>
    );
  }
}

Then you would map over it within the parent component as:

answer.map(answer =>
    <Question answer={answer} key={answer.id} />
)
over 4 years ago · Santiago Trujillo Denunciar

0

Another option is to add a state that save opened answer id, then checking if specific answer in that state or not.

let's see in action

class SomeComponent extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            opened: []
        }
        this.toggleShowHide = this.toggleShowHide.bind(this)
    }
    toggleShowHide(e){
        const id = parseInt(e.currentTarget.dataset.id)
        if (this.state.opened.indexOf(id) != -1){
            // remove from array
            this.setState({opened: this.state.opened.filter(o => o !== id)})
        } else {
            this.setState({opened: [...this.state.opened, id]})
        }
    }
    render(){
        return <ul>
            { this.state.answers.map(ans => (
                <li key={ans.id} data-id={ans.id}>
                    question 
                    <button onClick={this.toggleShowHide}>show answer</button>
                    <span
                     style={{ display: this.state.opened.indexOf(ans.id) !== -1 ? 'block' : 'none' }}>answer</span>
                </li>
             ))}
       </ul>
    }
}

Here is video in action https://www.youtube.com/watch?v=GJsPEsckB4w

over 4 years ago · Santiago Trujillo 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