How can one property of an object from an array be true if that property of other objects is false?

Viewed 51

I have an array State :

const [photos, setPhotos] = useState( [
{
  id:1,
  name:'Jack Stipen',
  isActive:true
},
{
  id:2,
  name:'Reshma Karim',
  isActive:false
},
{
  id:3,
  name:'Jahid Jader',
  isActive:false
},
{
  id:3,
  name:'Bindu Jemaiya',
  isActive:false
},
] );

I just want the property of one object to be true and the rest to be false.

I have a function to select an object property to be true . But undone!

const handleDefaultPhotoOnTable = ( id, e ) => {
        const exitPhotos = [...photos];
        const selectTablePhotoIndex = exitPhotos.findIndex( photo => photo.id === photoId );
        exitPhotos[selectTablePhotoIndex].isActive= e.target.checked;
        setPhotos( exitPhotos );
         ........

    };

Here you find my HTML Code:

     <tbody>
         {
          photos.map( ( photo ) => (
              <tr key={photo.id}>
                     <td>{photo.name}</td>
                      <td className="text-center">
          
                          <input onChange={( e ) => { handleDefaultPhotoOnTable( photo.id, e ); }} 
                           name='isActive' checked={photo.isActive} 
                           type='checkbox' 
                           id='defaultId' />
                       </td>
               </tr>
              ) )
           }
     </tbody>


     

Please help me.

1 Answers

You can use a map loop for this case like this:

setPhotos(
  photos.map((photo) =>
    photo.id === photoId
      ? { ...item, isActive: true }
      : { ...item, isActive: false }
  )
);
Related