One great new tool we have access to is the React Dev Tools. This is a browser extension that allows you to inspect your components in React. This becomes helpful when you want to inspect the state or props in a component. For example, props and state was very confusing when I first started learning React. I would pass some props down the same way I saw in class, but wasn't really sure if it was working.
Fear not! Even if you don't understand what props are, like I didn't, you can take baby steps and just make sure you are passing props down correctly by inspecting a components props and state.
Seeing props and state laid out like this also helps us visualize what props and state are. For example, we passed some props down from our App component to the RecipeContainer. Even though those recipes are a part of App's state, once they are passed down to the RecipeContainer, they do not become part of RecipeContainer's state. They are now props in RecipeContainer.
Seeing props like this also becomes useful when we want a child component to have different functionality based on two different parent components. Take this Flatiron Stocks lab for example. Whenever we click on a Stock component that belongs to the StockContainer, we want to add it to our PortfolioContainer. When we click on that same Stock component in the PortfolioContainer, we want that stock to be removed from our portfolio.
Unless we create buttons, we can only put one click action on our stock card.
A work-around would be for the PortfolioContainer and the StockContainer to pass down a remove and add function, respectively, to the Stock component. However, when we pass this function down, we give the function the same prop name. So now, depending on where this prop came from, it has different functionality in our Recipe component.
This might be hard to grasp just looking at our code, but when we look at our Dev Tools, we can see all of the individual Recipe components laid out, each with a different function, based on its parent.
We can also use
console.logs and where. First of all, a React component always has to render valid JSX. For now, what JSX exactly is doesn't matter, but if you see code that looks like HTML in your
Lastly, we can still use debuggers.
Since a lot of what happens in React works asynchronously, we might write out some code that in theory should run, but we just don't see anything happening on our screen. Adding a debugger helps you pause your code and you might see something happen that you weren't seeing before. If that happens, you'll know it's a timing issue, which can be solved by adding something like a setTimeout function to your code that needs to wait for another event to fire off first.
These are just the basics of debugging, and, of course, you'll run into more complex issues that require some more research. Knowing how to diagnose what might be going wrong in the first place is a good place to start, though.