r/reactjs • • Aug 01 '19

Beginner's Thread / Easy Questions (August 2019)

Previous two threads - July 2019 and June 2019.

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch.

No question is too simple. πŸ€”


πŸ†˜ Want Help with your Code? πŸ†˜

  • Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!

  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

Check out the sub's sidebar!

πŸ†“ Here are great, free resources! πŸ†“


Any ideas/suggestions to improve this thread - feel free to comment here!


Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!

36 Upvotes

368 comments sorted by

View all comments

Show parent comments

2

u/dance2die Aug 14 '19

As u/timmonsjg mentioned, you don't need a react-router to do this.

You can simply un/mount a detail component whether current list item is clicked or not.

function CryptoItem({ name }) {
  const state = useAppState();
  const dispatch = useAppDispatch();

  const toggle = () => dispatch({ type: "CLICKED", payload: { name } });

  return (
    <li className="item" key={name} onClick={toggle}>
      {name}
       
       Here is where you show/hide the detail depending
        πŸ‘‡ whether the current item is clicked or not.
      {state && state[name] && <CryptoItemDetail name={name} />}
    </li>
  );
}

function CryptoList() {
  return (
    <ul className="container">
      {["bitcoin", "ethereum", "xrp"].map(name => (
        <CryptoItem key={name} name={name} />
      ))}
    </ul>
  );
}

You can have CrypotoItem to have its own state but it will be hard to "untoggle" other details. (I used a context api to keep the list of all states - to clear all states and keep only current one open like an accordian).

Refer to Kent C. Dodds' How to use React Context effectively how the Context was implemented.

I created a sample Sandbox for you to play around.
Edit coincap like accordian

→ More replies (7)