how to import function in reactjs

Viewed 199

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.

2 Answers

Change

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

to

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

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>
Related