Search code examples
reactjscomponentsstateauth0react-props

Filter links in React Props


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 logged in. I have an isAuthenticated value that I use to check if the user is not logged in, but am unsure how I could use the variable to conditionally disable or not render the edit and delete button if the user is not logged in.


Solution

  • You can pass isAuthenticated around like this:

    render() {
      const { isAuthenticated } = this.props.auth0;
      //....
      { this.exerciseList(isAuthenticated) }
    } 
    
    exerciseList(isAuthenticated) {
            return this.state.exercises.map(currentexercise => {
              return <Exercise exercise={currentexercise} deleteExercise={this.deleteExercise} key={currentexercise._id} isAuthenticated={isAuthenticated}/>;
            })
    }
    

    Note that inside exerciseList, it's getting passed to your exercise. Then, you could refer to props.isAuthenticated and render conditionally based on the value (I'm using a ternary expression to return null if isAuthenticated is false):

    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>
          { props.isAuthenticated ?
            <td><Link to={"/edit/"+props.exercise._id}>edit</Link> | <a href="/#" onClick={() => { props.deleteExercise(props.exercise._id) }}>delete</a></td>
          : 
          <td></td>
          }
        </tr>
      )