Conditional rendering and List rendering
2021-04-23
React interview cheatsheet series
A quick answer in a interview would be something like:
In ReactJS you can create components that renders different code depends on the state of the app, so for example:
1function ConditionalRenderingComponent(props) { 2 const isTrue = props.isTrue; 3 return ( <p>It's { isTrue ? 'true' : 'false' }</p> ); 4} 5 6ReactDOM.render( 7 <ConditionalRenderingComponent isTrue={true} />, 8 document.getElementById('root') 9);
So our component is listening a state var or a prop and depends on its value, the component renders a block of code or other.
Lists and keys
Each time you render a list, you have to set a unique key to that list so react knows which elements (list items) are changed and which not, avoiding render more than the needed.
Important to mention ReactJS's key prop, which gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps the same DOM, even if the props changed. The exception to this is the key prop. This allows you to return the exact same element type, but force React to unmount the previous instance, and mount a new one.
Also to mention that using index as a key is an anti-pattern. If the prop 'key' is used to identify DOM elements which are unmounted and mounted again, if the key prop is the same again and again, Reacts think that the DOM is exactly the same than before, which is not the case.
So instead of doing this:
1todos.map((todo, index) => ( 2 <Todo {...todo} key={index} /> 3 )); 4}
Do this:
1todos.map((todo) => ( 2 <Todo {...todo} key={todo.id} /> 3 )); 4}
The only exception is when the list of elemets are static, they are not filtered or reorders,, or they don't have an id either.
See official doc: https://reactjs.org/docs/conditional-rendering.html.