I have multiple methods which render React components. I have put them inside methods to avoid calling components at multiple places with all the props. They are also being passed to another component.
renderComponentAbc = () => <Abc prop1={} prop2={} prop3={}/>;
renderComponentDef = () => <Def prop1={} prop2={} prop3={}/>;
renderComponentXyz = () => <Xyz prop1={} prop2={} prop3={}/>;
I want to render these one besides another in a component, so I tried this:
// Inside render method
<div>
{
props.renderComponentAbc();
props.renderComponentDef();
props.renderComponentXyz();
}
</div>
But above code throws error Syntax error: Unexpected token, expected }
. Is this not possible without wrapping each function call in a {}
? Removing ;
after function invocation doesn't help. Is it that {}
can only evaluate one expression?
To answer your question
Is it that {} can only evaluate one expression?
That is correct. You should use multiple expression blocks in your JSX if you have multiple render functions.
// Inside render method
<div>
{props.renderComponentAbc()}
{props.renderComponentDef()}
{props.renderComponentXyz()}
</div>
Also, you shouldn't use semicolons in JSX expressions.
Why do semicolons throw error in react JSX?
Another possible way is by wrapping the function calls in an Array:
// Inside render method
<div>
{[
props.renderComponentAbc(),
props.renderComponentDef(),
props.renderComponentXyz()
]}
</div>
This will require you to add key
props to the render methods though.
I do not know why you need that behavior, but it seems you can not do it.
From React docs : You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2
, user.firstName
, or formatName(user)
are all valid JavaScript expressions.
An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value . The value may be a number, a string, or a logical value. Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.