2

This code uses React version 0.14.

I am trying to set a var to a react component and return it. My eventual goal is to use a switch to assign different components based on some props. This is the part of my render statement not working:

var inputNumber = <InputNumber displayText={this.props.data.DisplayText} />;
return (
    {inputNumber}
);

This replacement code evaluates fine:

return (
    <InputNumber displayText={this.props.data.DisplayText}/>
);

This is the error message I get (InputDataItem is the component the above snippet is from):

Uncaught Error: Invariant Violation: InputDataItem.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

Clearly I have a gap in my syntax understanding.

I based my assumption on this working off of this part of the React documentation (4th code example): https://facebook.github.io/react/tips/if-else-in-JSX.html

0

2 Answers 2

3

It should be:

return (
  <div>
    {inputNumber}
  </div>
);

or simply:

return inputNumber;
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it'd be something simple. Thanks a bunch.
2

The {...} are only special inside JSX. In

return (
    {inputNumber}
);

there is no JSX. The {...} denote an object literal, even though it might not seem like one to you. What's new in ES2015 is something called short object notation, which allows you to omit the key. Your code is equivalent to

return (
    {inputNumber: inputNumber}
);

Either just return the inputNumber or put {...} inside JSX, as the other answer suggets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.