Class component with conditional table data props

Viewed 65

I have a react class component which consists of a table. The table has an edit and delete button that I want to disable if user is not loggedin. I have a isAuthenticated value that I use to check if the user is not logged

1 Answers

There are more than a way to skin this cat. One way is to create a custom component for the links

const DisablableLink = ({disabled = false, children, ...rest}) => 
  disabled 
  ? <span style={{color: '#CCCCCC'}}>{children}</span>
  : <Link {...rest} >{children}</Link>

This will let you do the following:

  1. You can disable the links by passing disabled as true
  2. stylize disabled and enabled component

Here is what your code would look like. (I am assuming isAuthenticated coming from the props.

const Exercise = props => (

    <tr>
      <td>{props.exercise.username}</td>
      <td>{props.exercise.description}</td>
      <td>{props.exercise.duration}</td>
      <td>{props.exercise.date.substring(0,10)}</td>
      <td>( 
        <DisablableLink disabled={!props.isAuthenticated} to={"/edit/"+props.exercise._id}>edit</DisablableLink> | <DisablableLink disabled={!props.isAuthenticated} onClick={() => { props.deleteExercise(props.exercise._id) }}>delete</DisablableLink>
      ) 
      </td>
    </tr>
  )

I have created a Codesandbox example for you

Related