Sunday, May 17, 2020

ReactJS Lists and keys

ReactJS Lists and keys


JavaScript Array


We have arrays in JavaScript that are indexed but have variable lengths. Their size is not fixed. JavaScript arrays are similar to JavaScript objects except for the keys, except objects can have non-integer keys like string literals, symbols, etc.

The map function can be used to transform a JavaScript array

var list=[10,12,13,5,7];
var newList=list.map(function(num){ return 2*num});
document.write(newList);

Output:
20,24,26,10,14

Transforming a javascript array into React elements array


Similarly, the map function can be used to transform normal JavaScript array into a React elements array.

(An unordered list)

function List(props)
{
  let ls=props.list;
  let rls=ls.map((opt)=><li>{opt}</li>);
  return <ul>{rls}</ul>;
}

var li=['BLue','Orange','Green','Red','Yellow'];
ReactDOM.render(<div><List list={li} /></div>,document.getElementById('root'));

OR

(Dropdown list)
function List(props)
{
  let ls=props.list;
  let rls=ls.map((opt)=><option>{opt}</option>);
  return <select>{rls}</select>;
}

var li=['Blue','Orange','Green','Red','Yellow'];
ReactDOM.render(<div><List list={li} /></div>,document.getElementById('root'));

Keys


The keys can be used to identify which element is element is changed, deleted, or added to the component. The keys are important when content is dynamic and it can be altered over time. Unique keys must be provided among siblings. It is not necessary to provide globally unique keys. 

For example,
function List(props)
{
  let ls=props.list;
  let rls=ls.map((opt)=><li key={opt.toString()}>{opt}</li>);
  return <ul>{rls}</ul>;
}

however, this is not good practice to use indices as keys, it may reduce the performance of the React application.

function Gallary(props) {
                             
  const pictable = props.pics.map((pic) =>
       <tr key={pic.id}>
            <td><img src={pic.src}/></td>
            <td><button></button></td>
            <td><h3>{pic.description}</h3></td>
        </tr>
      );

  return (
    <table>
      {pictable}
    </table>
  );
}

const pics = [
  {id: 1, src: 'https://cdn.pixabay.com/photo/2015/12/02/14/51/caudata-1073282__340.jpg',
 description: 'beautiful orchid-1'},
  {id: 2, src: 'https://cdn.pixabay.com/photo/2016/11/29/02/29/beautiful-1866867__340.jpg',
 description: 'beautiful orchid-2'}
];
ReactDOM.render(
  <Gallary pics={pics} />,
  document.getElementById('root')
);

Results will appear as,






The map function can also be embedded within JSX syntax to write in-line code.