-1

Why can't I do this in react?

import React from 'react';

export default class App extends React.Component {
    somefun() {
        return (<p>hello</p>);
    }
    render() {
        return ( 
            {somefun()}
        )
    }
 }

When I try I get a compile error

SyntaxError: C:\Users\karln\baeldung\my-app\src\App.js: Unexpected token, expected "{" (9:13)

   7 |  render() {
   8 |          return (
>  9 |                  {somefun()}
     |                            ^
  10 |          )
  11 |  }
  12 |  }

I'm new to react and getting through, but this one kind of vexes me.

2
  • You can use JSX in other functions. The problem here is that the brackets can only be used inside of the JSX tree. You can either eliminate the brackets completely, or wrap them into a JSX element: return (<div>{someFun()}</div>) Commented Apr 16, 2021 at 12:45
  • I saw that I could do (<div>{somefun()}</div>) but I thought that was messy. What is <>{somefun()}<> and what does it do? I assume that would not generate any html other than what is produced by somefun ? Commented Apr 16, 2021 at 12:48

4 Answers 4

1

You need root element

<> </>

or

React.Fragment or whatever the tag is

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

5 Comments

Can you clarify what you mean by React.Fragment ? Would that be instead of React.Component ?
Oh, I see, so it's longhand for <> </>.
Yes it is, to be honest i prefer longhand, it's way more clean
@SullivanTobias What is the definition of "clean" here?
Yes I should have been clearer I should say that in a context where the render is not super long you can use the shorthand But I find that when there are many more elements, I find the longhand much more meaningful. In the end I only use longhand now for comprehension reasons. But everyone has their own way of doing things in the end
1

You can use

<> {somefun()} </> 

This is React Fragment. It does not write any html tags like div, p...

Comments

0

{} isn't valid there. It's used to interpolate values in JSX (like <h1>{title}</h1>) but you aren't in a JSX element there.

1 Comment

Thanks for all the replies, exactly what I needed!
0

You need a root element first

render(){
return(
<div>
{somefun()}
</div>
)}

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.