tom clack
tom clack

Reputation: 191

how to import function in reactjs

AppFunction.js

export default function myFunction() {
  var str1 = "Hello ";
  var str2 = "world!";
  var res = str1.concat(str2);
  document.getElementById("demo").innerHTML = res;
}

App.js

import React, { Component } from 'react';
import myFunction  from './AppFunction';

class App extends Component {           
  render() {
    return (
      <div className="App">
        <button onclick="myFunction()">Try it</button>
        <p id="demo"></p>
      </div>
    );
  }
}

export default App;

I should to import an existing JavaScript library and then call it's functions.

componentDidMount() {
  myFunction()
}

When I write like this, working. But shows on screen without clicking the onclick button. I want to press the button and show it on the screen.

Upvotes: 2

Views: 508

Answers (2)

Hai Tien
Hai Tien

Reputation: 3117

You should use

export default function myFunction() {
  var str1 = "Hello ";
  var str2 = "world!";
  var res = str1.concat(str2);
  return res;
}

and

<button onClick={myFunction}>Try it</button>

Upvotes: 0

dotconnor
dotconnor

Reputation: 1786

Change

<button onclick="myFunction()">Try it</button>

to

<button onClick={myFunction}>Try it</button>

Upvotes: 6

Related Questions