Search code examples
javascriptreactjscomponentsternary

What is wrong here? Component with ternary inside


    export const Date = ({ startDate, endDate, displayInUserTime }) => {
    const parsedStartDate = moment.utc(startDate).format("ll");
    const parsedEndDate = moment.utc(endDate).format("ll");
    const parsedLocalStartDate = moment(startDate).format("ll");
    const parsedLocalEndDate = moment(endDate).format("ll");

    return (
        <Content column className="col-1">
            {displayInUserTime ? 
            (<div>{parsedStartDate}</div>
            {parsedStartDate !== parsedEndDate && <div>{parsedEndDate}</div>}) 
            :
            (<div>{parsedLocalStartDate}</div>
            {parsedLocalStartDate !== parsedLocalEndDate && <div>{parsedLocalEndDate}</div>})}
        </Content>
    );
};

Error: Parsing error: Unexpected token, expected ","

33 | {displayInUserTime ? 34 | ({parsedStartDate}

35 | {parsedStartDate !== parsedEndDate && {parsedEndDate}}) | ^ 36 | : 37 | ({parsedLocalStartDate} 38 | {parsedLocalStartDate !== parsedLocalEndDate && {parsedLocalEndDate}})}


Solution

  • You are returning multiple elements in the {} simplified code looks like bool?<one/><two/>:<three/><four/> the other answer changes the code to if statements but you could wrap your ternary in a React.Fragment: bool?<><one/><two/></>:<><three/><four/></>

    Your code could be:

    <Content column className="col-1">
      {displayInUserTime ? (
        <>
          <div>{parsedStartDate}</div>
          {parsedStartDate !== parsedEndDate && (
            <div>{parsedEndDate}</div>
          )}
        </>
      ) : (
        <>
          <div>{parsedLocalStartDate}</div>
          {parsedLocalStartDate !== parsedLocalEndDate && (
            <div>{parsedLocalEndDate}</div>
          )}
        </>
      )}
    </Content>