how you know which item is an image or button

Viewed 37

I am having a problem in pass image props in ReactJs

This is my code for that:component/Table/index. This component use for 2 tables (Order and Product) so I create to like this

import React from 'react';
import {Table, Image} from 'react-bootstrap';
import '../Table/index.css';
import Button from '../Button/index';

const TableItem = ({datas, columns}) => {
  return(
    <Table striped bordered hover>
      <thead>
        <tr> 
          {columns.map(name => <th>{name}</th>)}
        </tr>
      </thead>
      <tbody>
        <tr> 
          {datas.map(data => 
          <td>{data}</td>
          )}
        </tr>
      </tbody>
    </Table>
  );
}

export default TableItem;

and I have to import data for that column like this from app.js

 <TableItem columns={["No.", "Image", "Name", "Category", "Price", "Action"]} 
 datas={["1", "https://place-hold.it/100x150", "MIlk tea", "Milk tea", "100000", "button"]}
 />

As you see above I have imported the data for all column, but has a problem that, in column Image, I do not have <Image> tag for that so that can not be displayed for me the data of image link, and also I have 1 column is Action, in this column will have two buttons, Edit and delete for each row of each product And if I have many data, how can I retrieve it in app.js file

I do not have any idea to solve that, can anyone help me please, this is so hard for me because I very new on ReactJs

1 Answers

The question is how you know which item is an image or button.

If you know its always the one called "Image", you can search for it in the columns, get the index and use that in the loop:

const TableItem = ({datas, columns}) => {

  const imageColumnIndex = columns.indexOf('Image');
  const actionColumnIndex = columns.indexOf('Action');

  return(
    <Table striped bordered hover>
      <thead>
        <tr> 
          {columns.map(name => <th>{name}</th>)}
        </tr>
      </thead>
      <tbody>
        <tr> 
          {datas.map((data, index) => 
          <td>
            {index === actionColumnIndex ? (
              <React.Fragment>
                {data.includes('edit') && <button type="button">Edit</button>}
                {data.includes('delete') && <button type="button">Delete</button>}
              </React.Fragment>
            ) : (
              index === imageColumnIndex ? <img src={data}/> : data
            )}
          </td>
          )}
        </tr>
      </tbody>
    </Table>
  );
}

Then in your app.js, using edit and delete as button examples:

const columns = ["No.", "Image", "Name", "Category", "Price", "Action"];
const datas = ["1", "https://place-hold.it/100x150", "MIlk tea", "Milk tea", "100000", "edit,delete"];

return <TableItem columns={columns} datas={datas}/>

Note: if you havent seen the <condition? ? <true> : <false> yet, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Related