1003

Is there a way to only add attributes to a React component if a certain condition is met?

I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.

The example below should explain what I want, but it doesn't work.

(Parse Error: Unexpected identifier)

function MyInput({isRequired}) {
  return <input classname="foo" {isRequired ? "required" : ""} />
}
golopot
  • 10,726
  • 6
  • 37
  • 51
Remi Sture
  • 12,000
  • 5
  • 22
  • 35
  • 3
    May be one comment help someone, i found out React 16.7 ***doesnt rerenders*** and update the component's html attributes if you changed only them in a store (f.e. redux) and tied to component. This means the component has f.e.```aria-modal=true```, you push the changes (to false) to the store of **aria/data** attributes, but nothing else is changed (such as component's content or class or variables in there) as the result ReactJs will not update **aria/data** attrs in that components. I've been messing around about whole day to realise that. – Alexey Nikonov Feb 13 '19 at 09:46

29 Answers29

874

Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:

const InputComponent = function() {
    const required = true;
    const disabled = false;

    return (
        <input type="text" disabled={disabled} required={required} />
    );
}

will result in:

<input type="text" required>

Update: if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30 and 167 of the DOMProperty.js file.

Gian Marco Toso
  • 11,676
  • 5
  • 29
  • 38
  • 78
    Generally `null` means "act like I didn't specify it at all". For boolean dom attributes true/false is preferred over repeating the attribute name/false, e.g. `` compiles to `React.createElement('input', {disabled: true})` – Brigand Jul 01 '15 at 14:31
  • I agree. I repeat the name because I had problems in the past with certain browsers and the habit stuck with me so much that I added in manually the `="required"` part. Chrome actually did render just the attribute without the value. – Gian Marco Toso Jul 01 '15 at 14:33
  • 13
    `readonly` never gets added because React is expecting the attribute `readOnly` (with a capital O). – Max Feb 22 '16 at 13:54
  • 14
    Thanks! Make sure the value is not just an empty string or zero, these may not get removed. For example, you could pass a value like this, and it should make sure it is removed if it evaluates to false: `alt={props.alt || null}`. – Jake Jul 27 '16 at 05:35
  • 11
    Thanks, @Jake. I had tried setting the attribute to `false`, but only `null` made sure the attribute was actually removed. – Nathan Arthur Jun 15 '17 at 14:07
  • 3
    I am getting `Warning: Received \`false\` for a non-boolean attribute \`active\`...` – JBis Apr 24 '19 at 18:41
  • 1
    This isn't the correct way to do this anymore. React will give a console warning (`Received false for a non-boolean attribute 'prop'`) suggesting you use this format instead: `prop={condition ? value : undefined}`. Meaning, you should be passing `undefined`, not `false`. – Paul Nov 17 '21 at 18:55
  • @Paul it depends on the prop. As you can see in React's own source code, `required` and `disabled` are both booleans, so this is, in fact, the correct way to do it, but it might not be for props that are expecting a value instead of true/false (https://github.com/facebook/react/blob/main/packages/react-dom/src/shared/DOMProperty.js#L318) – Gian Marco Toso Nov 17 '21 at 20:14
  • regarding React throwing error when "true", "false" used as suggested in above answer, it is because you use string values e.g disabled={"false"} will throw error, `disabled={false}` won't throw any error – Muhammad Uzair Jun 14 '22 at 14:47
597

juandemarco's answer is usually correct, but here is another option.

Build an object how you like:

var inputProps = {
  value: 'foo',
  onChange: this.handleChange
};

if (condition) {
  inputProps.disabled = true;
}

Render with spread, optionally passing other props also.

<input
    value="this is overridden by inputProps"
    {...inputProps}
    onChange={overridesInputProps}
 />
jonschlinkert
  • 10,872
  • 4
  • 43
  • 50
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • 28
    This is actually very useful, especially when adding many properties conditionally (and I personally had no idea it could be done this way). – Gian Marco Toso Jul 01 '15 at 14:38
  • 1
    Very elegant, but shouldn't it be inputProps.disabled = true? – Joppe Jan 16 '16 at 17:50
  • very simple, i have made my code more readable with out having multiple conditions. – Naveen Setty Aug 29 '19 at 21:51
  • 1
    If anyone cares about the precise semantics of this "sugar," you can look at the script that your .jsx is transpiled into you'll see that a function `_extends` has been added to it, which will (under normal circumstances) take the `props` constructed from the "normal attributes" and apply `Object.assign(props, inputProps)`. – Nathan Chappell Jan 31 '20 at 13:12
578

Here is an example of using Bootstrap's Button via React-Bootstrap (version 0.32.4):

var condition = true;

return (
  <Button {...(condition ? {bsStyle: 'success'} : {})} />
);

Depending on the condition, either {bsStyle: 'success'} or {} will be returned. The spread operator will then spread the properties of the returned object to Button component. In the falsy case, since no properties exist on the returned object, nothing will be passed to the component.


An alternative way based on Andy Polhill's comment:

var condition = true;

return (
  <Button bsStyle={condition ? 'success' : undefined} />
);

The only small difference is that in the second example the inner component <Button/>'s props object will have a key bsStyle with a value of undefined.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arman Yeghiazaryan
  • 6,194
  • 1
  • 16
  • 23
  • 5
    @Punit, The spread operator has a lower precedence than the conditional operator, so the condition is evaluated first, (either `{bsStyle: 'success'}` or `{}` results from it), then that object is spread. – Victor Zamanian Oct 17 '17 at 13:21
  • 10
    Would the following do the same `` I find the syntax slightly easier, passing `undefined` will omit the property. – Andy Polhill Jan 05 '18 at 18:00
  • 3
    @AndyPolhill looks good to me and much easier to read the code, the only small difference is that in your code example inner component ``'s `props` object will have a key `bsStyle` with value of `undefined`. – Arman Yeghiazaryan Jan 06 '18 at 02:39
  • @AndyPolhill the reason the syntax seems harder to read is because it is missing some implicit parentheses which makes the example look foreign and harder to understand. Editing the example to add parentheses. – Govind Rai Jan 30 '18 at 15:38
  • @ArmanYeghiazaryan Just wondering, but is there any negative impact on having a key with value `undefined`? What would be the shortcoming here? – Giraldi May 17 '18 at 09:04
  • @Giraldi, good question. In the moment when I've posted my answer, I've tried to use **React-Bootstrap**'s **Button** component. But the thing was that I was unable to set the value to `undefined` and in result get the default **Button** component without any style. After a while they've fixed this problem. It seems like they've tried to go through component's prop keys. – Arman Yeghiazaryan May 17 '18 at 22:49
  • Just noting that this also works for me without React-Bootstrap, just using the normal `button` component: `` – Cardano Jun 29 '18 at 00:12
  • You don't need a ternary with `undefined`, you can simply have `` or `` – Raphael Pinel Jan 21 '21 at 06:24
  • 3
    This was the only solution that allowed a radio button to not throw a warning on a `checked` value being set without an `onChange` set (even though `checked` was being set to false). So `{...(checked ? {checked} : {})}`. Thanks for the solution! – ScottS Jan 23 '21 at 18:27
  • 2
    Solved my problem! Thanks. Here is an example of how I used it, spreading React Native style classes conditionally: `style={{...(isReadOnly ? styles.readOnly : {}), ...styles.baseStyle }}` Then, inside the component, you can mix it into whatever styles the component is using: `Hello World` – C.T. Bell Dec 23 '21 at 14:23
  • I needed to conditionally add a readOnly attribute to an input so the first example worked perfectly with some adjustments on my end: `{...getVanStatus === "success" && !warrantyReg.van_model ? `` : `readOnly`}`. though i don't understand what the spread operator does outside of being a magic three dots – Edward Dec 14 '22 at 23:51
  • Hi @Edward, you'll need to use this bit of code `{...(getVanStatus === "success" && !warrantyReg.van_model ? {} : {readOnly: true})}` instead. – Arman Yeghiazaryan Dec 15 '22 at 02:12
  • @ArmanYeghiazaryan readOnly isn't a variable, it's the actual readonly attribute I'm adding to the input in react with the desired output as ``. Would `{readOnly: true}` output the attribute in the input as I showed? – Edward Dec 16 '22 at 17:21
  • @Edward, so if you're setting `readOnly` attribute specifically for `` tag, then the best use would be `readonly={getVanStatus === "success" && !warrantyReg.van_model}`, because React itself automatically adds and removes `readonly` HTML attribute from the final render, so you don't need to worry about removing/adding the attribute itself. Side note, if you would've used only vanilla HTML (not React.js), setting readonly="false", would've caused you to actually enable the read-only state, which might be illogical, but React.js handles it as expected. – Arman Yeghiazaryan Dec 18 '22 at 06:48
  • @ArmanYeghiazaryan thanks for clarifying. I didn't test the readOnly="false" since the attribute didn't seem to support that behavior, but good to know react will sort it accordingly. i love learning a new weird javascript/react thing. I actually have a doc titled "weird react/js stuff" – Edward Dec 19 '22 at 19:56
  • 1
    this most accurately addresses the general question the original asker asked – drussell Jan 23 '23 at 22:31
210

Here is an alternative.

var condition = true;

var props = {
  value: 'foo',
  ...(condition && { disabled: true })
};

var component = <div {...props} />;

Or its inline version

var condition = true;

var component = (
  <div value="foo" {...(condition && { disabled: true })} /> 
);
jonschlinkert
  • 10,872
  • 4
  • 43
  • 50
Season
  • 4,056
  • 2
  • 16
  • 23
  • 14
    I like this approach, it makes me cool among my workmates. Kidding aside, from the looks of it, the props are just passed as a key-value pair after all, is that correct? – JohnnyQ Jan 31 '17 at 09:30
  • 3
    If `condition` is false, this will try to expand/iterate over false, which I don't think is correct. – Lars Nyström Feb 14 '17 at 13:14
  • 2
    @LarsNyström, That makes sense. The spread operator accepts only iterables, where `false` is not one. Just check with Babel. This works with it when `condition` evaluates to false since the way Babel implements the operator. Though a trivial workaround could be `...( condition ? { disabled: true } : {} )`, it becomes a bit verbose then. Thanks for this nice input! – Season Feb 14 '17 at 14:23
  • +1 This approach is required if you want to conditionally output `data-*` or `aria-*` attributes, as they're a special case in JSX, so `data-my-conditional-attr={ false }` will output `data-my-conditional-attr="false"` rather than omitting the attribute. https://facebook.github.io/react/docs/dom-elements.html – ptim Jul 26 '17 at 07:36
  • Any idea how to do this with an attribute that takes an array or jsx expression? `columns={{ xs: 4, sm: 8, md: 12 }}` say if I wanted to change the numbers based on a boolean? – Jared Rice Jul 13 '22 at 19:42
  • Lars is right: the spread operator requires an object. If the condition is false, there is no object. – Phierru Sep 24 '22 at 12:54
57

Here's a way I do it.

With a conditional:

<Label
    {...{
      text: label,
      type,
      ...(tooltip && { tooltip }),
      isRequired: required
    }}
/>

I still prefer using the regular way of passing props down, because it is more readable (in my opinion) in the case of not have any conditionals.

Without a conditional:

<Label text={label} type={type} tooltip={tooltip} isRequired={required} />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tony Tai Nguyen
  • 1,502
  • 13
  • 27
  • Could you pls explain how this part works - `...(tooltip && { tooltip }),`? It does work on component but when I try to use something like this in the code I get an error meaning that I try to spread non-iterable value – skwisgaar Mar 16 '20 at 20:17
  • 1
    probably because `falseyValue && {}` will return false, so its likely you are spreading on false eg `...(false)`. much better to use full expression so the spread continues to behave `...(condition ? {foo: 'bar'} : {})` – random-forest-cat Apr 20 '20 at 13:17
36

Let’s say we want to add a custom property (using aria-* or data-*) if a condition is true:

{...this.props.isTrue && {'aria-name' : 'something here'}}

Let’s say we want to add a style property if a condition is true:

{...this.props.isTrue && {style : {color: 'red'}}}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mina Luke
  • 2,056
  • 1
  • 20
  • 22
22

You can use the same shortcut, which is used to add/remove (parts of) components ({isVisible && <SomeComponent />}).

class MyComponent extends React.Component {
  render() {
    return (
      <div someAttribute={someCondition && someValue} />
    );
  }
}
GijsjanB
  • 9,944
  • 4
  • 23
  • 27
  • 3
    If `someCondition` is true but `someValue` is falsy (e.g. `false` itself, or `0`, etc.), does the attribute still get included? This is important if it is necessary to explicitly include a falsy value, e.g. a `0` for a coordinate attribute, etc. – Andrew Willems Dec 14 '16 at 13:25
  • Normally, the attribute is omitted, but not in the case of `data-*` and `aria-*`, see my comment above. If you quote the value, or cast it as a String, the attribute will display: eg `someAttr={ \`${falsyValue}\` }` could render `someAttr="false"` – ptim Jul 26 '17 at 07:41
14

If you use ECMAScript 6, you can simply write like this.

// First, create a wrap object.
const wrap = {
    [variableName]: true
}
// Then, use it
<SomeComponent {...{wrap}} />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
snyh
  • 1,225
  • 14
  • 19
10

Using undefined works for most properties:

const name = "someName";

return (
    <input name={name ? name : undefined} />
);
Tim
  • 2,805
  • 25
  • 21
7

This should work, since your state will change after the Ajax call, and the parent component will re-render.

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>
    );
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Parker
  • 12,724
  • 5
  • 37
  • 58
6

Given a local variable isRequired You can do the following in your render method (if using a class) or return statement (if using a function component):

 <MyComponent required={isRequired ? 'true' : undefined} />

In this case, the attribute will not be added if isRequired is undefined, false, or null (which is different from adding the attribute but setting it to 'false'.) Also note that I am using strings instead of booleans in order to avoid a warning message from react (Boolean value received on non-boolean attribute).

Neil Girardi
  • 4,533
  • 1
  • 28
  • 45
4
  1. For some boolean attributes listed by React [1]:
<input disabled={disabled} />

// renders either `<input>` or `<input disabled>` 
  1. For other attributes:
<div aria-selected= {selected ? "" : undefined} />

// renders either `<div aria-selected></div>` or `<div></div>`

[1] The list of boolean attributes: https://github.com/facebook/react/blob/3f9480f0f5ceb5a32a3751066f0b8e9eae5f1b10/packages/react-dom/src/shared/DOMProperty.js#L318-L345

golopot
  • 10,726
  • 6
  • 37
  • 51
3

For example using property styles for custom container

const DriverSelector = props => {
  const Container = props.container;
  const otherProps = {
    ...( props.containerStyles && { style: props.containerStyles } )
  };

  return (
    <Container {...otherProps} >
2

In React you can conditionally render Components, but also their attributes, like props, className, id, and more.

In React it's very good practice to use the ternary operator which can help you conditionally render Components.

An example also shows how to conditionally render Component and its style attribute.

Here is a simple example:

class App extends React.Component {
  state = {
    isTrue: true
  };

  render() {
    return (
      <div>
        {this.state.isTrue ? (
          <button style={{ color: this.state.isTrue ? "red" : "blue" }}>
            I am rendered if TRUE
          </button>
        ) : (
          <button>I am rendered if FALSE</button>
        )}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Juraj
  • 260
  • 2
  • 5
  • 1
    This can get really messy with lots of attributes. I like the spread variant better. – Remi Sture Jan 19 '18 at 07:06
  • Yes Your are right but this is for someone who need to get overview I will make another example. But want keep things simple. – Juraj Jan 19 '18 at 17:08
2

From my point of view the best way to manage multiple conditional props is the props object approach from @brigand. But it can be improved in order to avoid adding one if block for each conditional prop.

The ifVal helper

rename it as you like (iv, condVal, cv, _, ...)

You can define a helper function to return a value, or another, if a condition is met:

// components-helpers.js
export const ifVal = (cond, trueValue=true, falseValue=null) => {
  return cond ? trueValue : falseValue
}

If cond is true (or truthy), the trueValue is returned - or true. If cond is false (or falsy), the falseValue is returned - or null.

These defaults (true and null) are, usually the right values to allow a prop to be passed or not to a React component. You can think to this function as an "improved React ternary operator". Please improve it if you need more control over the returned values.

Let's use it with many props.

Build the (complex) props object

// your-code.js
import { ifVal } from './components-helpers.js'

// BE SURE to replace all true/false with a real condition in you code
// this is just an example

const inputProps = {
  value: 'foo',
  enabled: ifVal(true), // true
  noProp: ifVal(false), // null - ignored by React
  aProp: ifVal(true, 'my value'), // 'my value'
  bProp: ifVal(false, 'the true text', 'the false text') // 'my false value',
  onAction: ifVal(isGuest, handleGuest, handleUser) // it depends on isGuest value
};

 <MyComponent {...inputProps} />

This approach is something similar to the popular way to conditionally manage classes using the classnames utility, but adapted to props.

Why you should use this approach

You'll have a clean and readable syntax, even with many conditional props: every new prop just add a line of code inside the object declaration.

In this way you replace the syntax noise of repeated operators (..., &&, ? :, ...), that can be very annoying when you have many props, with a plain function call.

Our top priority, as developers, is to write the most obvious code that solve a problem. Too many times we solve problems for our ego, adding complexity where it's not required. Our code should be straightforward, for us today, for us tomorrow and for our mates.

just because we can do something doesn't mean we should

I hope this late reply will help.

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
2

One way to do this is to use the spread operator (...) to pass a dynamic object of props to your component.

function MyInput({isRequired}) {
 const inputProps = { className: 'foo' };

 if (isRequired) {
  inputProps.required = true;
 }
 return <input {...inputProps} />;
}

In this code, we first create an object inputProps with the className property. Then, if the isRequired prop is true, we add the required property to the inputProps object. Finally, we pass the inputProps object to the input component using the spread operator (...), which will dynamically add the className and required attributes to the input element.

Note that we're not adding the readOnly attribute in this example, but you could add it in a similar way by checking another prop and conditionally adding it to the inputProps object.

1
<input checked={true} type="checkbox"  />
aadilraza339
  • 103
  • 3
1

In react functional component you can try something like this to omit unnecessary tag property.

<div className="something" ref={someCondition ? dummyRef : null} />

This works for me if I need to omit tags like ref, class, etc. But I don't know if that's work for every tag property

Vishav
  • 11
  • 1
1
<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>
amatinya
  • 31
  • 6
1

You must set as undefined the value for when you do not need the attribute Example:

<a data-tooltip={sidebarCollapsed?'Show details':undefined}></a>
jlizanab
  • 635
  • 7
  • 6
1

The accepted answer did not work for me when using Apollo's MockedProvider component.

What worked:

const props = {
    mocks: mockedApolloResponse ?? undefined, // simplified logic to make this example shorter
};

return <MockedProvider {...props}>{children}</MockedProvider>

Extra context:

I think the reason is that while mocks is optional on MockedProviderProps, it has to be of type ReadonlyArray<MockedResponse> when present.

In my IDE, writing this line of code caused resulted in a warning:

<MockedProvider mocks={mockedApolloResponse ?? undefined}</MockedProvider>

The warning was: Type ReadonlyArray<MockedResponse> | undefined is not assignable to type ReadonlyArray<MockedResponse>.

Retropiaf
  • 219
  • 3
  • 8
1

Use the conditional (ternary) operator from JavaScript within the JSX expression to conditionally add attributes to a React component based on a certain circumstance. However, in order to add the attribute dynamically, you must use the proper syntax.

Your example has a syntax error since you are attempting to add the "required" property via string interpolation. Instead, you must encapsulate the attribute and its value in curly brackets '{}'.

This modified version of your code appropriately adds the "required" property to the input component in a conditional manner and adds it to the input component:function MyInput({ isRequired }) { return <input className="foo" {isRequired ? 'required' : null} />; } The "required" property is conditionally added in this code using the isRequired prop. The property is inserted with the value "required" if isRequired is true. Otherwise, the property is skipped if isRequired is false or null.

Keep in mind that classname, not class, is used to specify the element's CSS class.

If you need to conditionally add it depending on a different circumstance, be sure to handle the readOnly property in a manner that is comparable as well.

0

Considering the post JSX In Depth, you can solve your problem this way:

if (isRequired) {
  return (
    <MyOwnInput name="test" required='required' />
  );
}
return (
    <MyOwnInput name="test" />
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Viktor Kireev
  • 1,200
  • 1
  • 8
  • 17
0

I think this may be useful for those who would like attribute's value to be a function:

import { RNCamera } from 'react-native-camera';
[...]

export default class MyView extends React.Component {

    _myFunction = (myObject) => {
        console.log(myObject.type); //
    }

    render() {

        var scannerProps = Platform.OS === 'ios' ? 
        {
            onBarCodeRead : this._myFunction
        } 
        : 
        { 
            // here you can add attribute(s) for other platforms
        }

        return (
            // it is just a part of code for MyView's layout
            <RNCamera 
                ref={ref => { this.camera = ref; }}
                style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center', }}
                type={RNCamera.Constants.Type.back}
                flashMode={RNCamera.Constants.FlashMode.on}
                {...scannerProps}
            />
        );
    }
}
RadekR
  • 503
  • 3
  • 10
0

in an easy way

const InputText= ({required = false , disabled = false, ...props}) => 
         (<input type="text" disabled={disabled} required={required} {...props} />);

and use it just like this

<InputText required disabled/>
malek
  • 9
  • 2
0

In addition, you can make other value to Boolean

const MyComponent = function() {
    const Required = "yes";

    return (
         <input
                      required={Required === "yes"}
                      type="text"
                      key={qs.Name}
                      name="DefaultValue"
                      label={qs.QuestionTitle}
                      onChange={(event) => handleInputChange(index, event)}
                      placeholder={qs.QuestionTitle}
                    />
    );
}
Majedur
  • 3,074
  • 1
  • 30
  • 43
0

If it is for a limited number of properties this will do


    function MyInput({isRequired}) {
        if (isRequired) {
            return <input classname="foo" isRequired={isRequired} />
        }
        return <input classname="foo" />
    }

If you have a large number of properties, it will be difficult to write if else conditions for every property and return accordingly. For that, you can push those properties in an object and use the spread operator in the returned element.

    function MyInput({ prop1, prop2, ...propN }) {
        const props = {};
        if (prop1) props.prop1 = prop1;
        .
        .
        .
        if (propN) props.propN = propN;
        return <input classname="foo" {...props} />
    }
0

Here is a simple example:

function Input({att}) {
  return (
      <input {...att}></input>
  )
 }

ReactDOM.render(
  <Input att={{name: 'username', required: true, placeholder: 'username'}}/>,
  document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 25 '23 at 08:26
-2

In React, we pass values to component from parent to child as Props. If the value is false, it will not pass it as props. Also in some situation we can use ternary (conditional operator) also.