Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
How can I set up state to allow one child component to render another

I have a main component which has two child components and six of each.

Something like this:

    <Main>
      <Component1 />
      <Component1 />
      <Component1 />
      <Component1 />
      <Component1 />
      <Component1 />
      <Component2 />
      <Component2 />
      <Component2 />
      <Component2 />
      <Component2 />
      <Component2 />
    </Main>

My goal is to be able to render a specific Component2 based on a toggle from Component 1.

So clicking the first Component1 would toggle the render of the first Component2

I've tried something like this in my main component:

  const [component2Visible, setcomponent2Visible] = useState([false, true, false, false, false, false])

But I don't think this is the right direction at all.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here is an approach that I might employ:

// state variables to hold arguments to generate Component1 & Component2
// Component1 args have a prop named 'hideC2' (initially set to false)
const [comp1Args, setComp1Args] = useState([{hideC2: false, ...}, {hideC2: false, ....}, {}]);
const [comp2Args, setComp2Args] = useState([{}, {}, {}]);
.
.
.
// Iterate over the two args arrays to generate Components
// Use '.filter' on comp2Args to 'hide' those where 'hideC2' is set to true
return (
  <Main>
    {
      comp1Args.map((args, idx) => (
        <Component1
          key={idx}
          args={args}
          onToggleC2={() => setComp1Args(prev => {
            const curr = [...prev];
            curr[idx].hideC2 = !prev[idx].hideC2;
            return [...curr]
          })}
        />
      ))
    }
    {
      comp2Args
      .filter((el, idx) => (comp1Args[idx].hideC2 !== true))
      .map((args, idx) => (
        <Component2 key={idx} args={args}/>
      ))
    }
  </Main>
);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!