steeleye / recruitment-ext

13 stars 25 forks source link

Nithin Amirineni_Front End #214

Open Nithinamr03 opened 1 year ago

Nithinamr03 commented 1 year ago

1.A) React's List component can be created using either the built-in HTML elements for unordered lists and list items, or a custom component. The List component takes an array of data as input and maps over each element to generate a corresponding list item, which is typically displayed as a separate React component. Additional elements like buttons or icons may also be included in the List component to enable user interaction, such as removing an item using a delete button.

2.A) There are a few issues with the code for the 'SingleListItem' component. Firstly, the 'onClickHandler' prop is currently being called immediately upon rendering, rather than being stored as a function for later use. Additionally, the 'isSelected' prop is receiving the 'selectedIndex' state value as a number instead of a boolean value, which is what is expected. To fix this, the code should be changed to use "isSelected={selectedIndex === index}" instead of "isSelected={selectedIndex}". Lastly, the propTypes for items in the 'WrappedListComponent' should be defined as "PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired }))" instead of "PropTypes.array(PropTypes.shapeOf({ text: PropTypes.string.isRequired }))".

3.A)

The modified code is as follows: `import React, { useState, useEffect, memo } from 'react'; import PropTypes from 'prop-types';

// Single List Item const WrappedSingleListItem = ({ index, isSelected, onClickHandler, text, }) => { return ( <li style={{ backgroundColor: isSelected ? 'green' : 'red'}} onClick={() => onClickHandler(index)}

{text}

); }; WrappedSingleListItem.propTypes = { index: PropTypes.number, isSelected: PropTypes.bool, onClickHandler: PropTypes.func.isRequired, text: PropTypes.string.isRequired, };

const SingleListItem = memo(WrappedSingleListItem);

// List Component const WrappedListComponent = ({ items, }) => { const [selectedIndex, setSelectedIndex] = useState(null);

useEffect(() => { setSelectedIndex(null); }, [items]);

const handleClick = index => { setSelectedIndex(index); };

return ( <ul style={{ textAlign: 'left' }}> {items.map((item, index) => ( <SingleListItem onClickHandler={() => handleClick(index)} text={item.text} index={index} isSelected={selectedIndex === index} /> ))}

) }; WrappedListComponent.propTypes = { items: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired })), };

WrappedListComponent.defaultProps = { items: null, };

const List = memo(WrappedListComponent);

export default List; `