1

So I'm using React to create a web app and I'm just working with only js files and css files, no html. I have a js file like this with some html code and some js code:

class Teams extends Component {
    state = {
        teams: []
    }

    componentDidMount() {
        ...
    }

    abc = () => {
        ...
    };

    render() {
        return (
            <Container>
               <Row className="space"></Row>
               <br></br>
               <br></br>
               <Row className="about-row"><h3>Teams</h3></Row>
               <br></br>
               <br></br>
               <Row className="about text-center">
                 {
                    this.abc()
                  }
               </Row>
            </Container>
        );
    }
}

export default Teams;

Basically I was wondering if there was a way to insert js code between html tags; I.e. Is there a way to do something like this:

<div>
   //js code 
   let x = "hello";
   console.log(x);
</div>

I've tried using html script tags and inserting js code in between but it doesn't work. Would I have to make a function outside the html tags and just call that function from inside the tags?

2 Answers 2

1

You can't declare variables inside of JSX code, but you can access the variables and functions declared before. To insert JS inside JSX you have to use brackets {} around your JS code.

ex:

render() {
  let someVariable = {id: 1: name: "x"}
  console.log(someVariable)
  return(
    <div>
      {JSON.stringfy(someVariable)} // brackets here
    </div>
  )
}

Link to docs: How to add JS in JSX

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

2 Comments

Thank you so much!
Get a few more rep so you can please upvote the rest of the answers.
0

Use brackets around your code so that React distinguishes it from HTML and doesn't render the code.

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.