Andre Tran
Andre Tran

Reputation: 67

how to include javascript between html tags all within a javascript file

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?

Upvotes: 1

Views: 132

Answers (2)

Carlos Eust&#225;quio
Carlos Eust&#225;quio

Reputation: 176

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

Upvotes: 1

new Q Open Wid
new Q Open Wid

Reputation: 2283

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

Upvotes: 0

Related Questions