Home > Enterprise >  Conditional rendering according to props
Conditional rendering according to props

Time:06-01

I am passing "winners" as a prop to my PastWinner component. How can I conditionally render my winner component if and only if my {winner.baseId} is greater than my currentRound (variable from the context)?

This is my current code

import { useContext } from 'react';
import { CanContext } from '../context/canContext';

const PastWinner = ({ winner }) => {
  const { currentRound } = useContext(CanContext);
  return (
    <>
      <td className='px-4 py-2'>{winner.baseId}</td>
      <td className='px-4 py-2'>{winner.respondee}</td>
    </>
  );
};
export default PastWinner;

I tried to do something like this but it dosen't work

return (
  {winner.baseId > currentRound ? (
    <>
    <td className='px-4 py-2'>{winner.baseId}</td>
    <td className='px-4 py-2'>{winner.respondee}</td>
  </>
  ): (<></>)}
)

The result of the winner object is as below:

{
baseId: "0"
originalResponse: "great"
respondee: "0x9d95bcaa5b609fa97a7ec860bec115aa94f85ba9"
submittedAt: "2022-06-01T05:24:03.218Z"
voters: ['0x39c878a3df98002ddba477a7aa0609fb5a27e2ff']
votes: 1
__v: 0
_id: "6296f7f3fe1858980b69dd2f"
}

CodePudding user response:

Based on the contents of your winner object, the property baseId seems to be of type string.

You should not compare values of different types in such a way.

So this will not necessarily resolve your issue, due to the way comparisons work in JS.
But it may point to a different problem. Not to mention that it is simply incorrect..

There are 3 main methods of parsing to an integer in JS.

  1. Adding a before the variable name when referring to it:
return (
  { winner.baseId > currentRound && (
    <>
      <td className='px-4 py-2'>{winner.baseId}</td>
      <td className='px-4 py-2'>{winner.respondee}</td>
    </>
  )}
)
  1. Using the Number method:
return (
  {Number(winner.baseId) > currentRound && (
    <>
      <td className='px-4 py-2'>{winner.baseId}</td>
      <td className='px-4 py-2'>{winner.respondee}</td>
    </>
  )}
)
  1. Using the parseInt function.
return (
  {parseInt(winner.baseId, 10) > currentRound && (
    <>
      <td className='px-4 py-2'>{winner.baseId}</td>
      <td className='px-4 py-2'>{winner.respondee}</td>
    </>
  )}
)

I recommend using parseInt.

Note: The second parameter of parseInt represents the radix/base value.
It is not optional and must be added.

P.S. make sure that currentRound is a number as well.

CodePudding user response:

try this one :

  if(winner?.baseId > currentRound){
    return (<>
      <td className='px-4 py-2'>{winner?.baseId}</td>
      <td className='px-4 py-2'>{winner?.respondee}</td>
    </>)
  }else{
    return <></>
  }
  • Related