Mr. Robot
Mr. Robot

Reputation: 1824

Conditional render based on integer prop value

I am trying to conditionally render jsx based on the integer value of a prop. In my example below, the prop depth varies from 0 - 4. The code below returns the error Node(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. depth is 0, so why won't it render? Thanks in advance.

import React from 'react';

function Node({ type, name, depth }) {

  if (depth === 0) {
    return (
      <div>
        {type}
        {name}
        {depth}
      </div>
    );
  }
}

export default Node;

Upvotes: 0

Views: 474

Answers (3)

niks
niks

Reputation: 466

You need to return outside of if block also

function Node({ type, name, depth }) {
if (depth === 0) {
  return (
    <div>
      {type}
      {name}
      {depth}
    </div>
  );
}
return null;

}

Upvotes: 0

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You can have a condition inside the return as well:

import React from 'react';

function Node({ type, name, depth }) {
    return (
      {depth === 0?
        <div>
          {type}
          {name}
          {depth}
        </div>
      : null}    
    );  
}

export default Node;

Upvotes: 1

Dupocas
Dupocas

Reputation: 21317

You always need to return from render:

import React from 'react';

function Node({ type, name, depth }) {

  if (depth === 0)
    return (
      <div>
        {type}
        {name}
        {depth}
      </div>
    );

    return null

}

export default Node;

Upvotes: 2

Related Questions