0

So I have a react-js script that I have a core/main.js and the main app.js file.

The data in main.js won't appear in the div "welcome" in app.js - when I call the function that should fire it.

main.js

import React from 'react';
import ReactDOM  from 'react-dom';


export default function tick() {
    const element = (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {new Date().toLocaleTimeString()}.</h2>
      </div>
    );
    // highlight-next-line
    ReactDOM.render(element, document.getElementById('welcome'));
  }

App.js

import React from 'react';
import tick from './core/Main.js'
//import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">


          <div id="welcome"></div>
          {tick}

      </header>
    </div>
  );
}

export default App;

How can I get this to show? I am trying to better understand this type of functions.

halfer
  • 19,824
  • 17
  • 99
  • 186
RussellHarrower
  • 6,470
  • 21
  • 102
  • 204

1 Answers1

0

You should turn your function tick into a component (e.g. Tick, just to name in properly):

export default function Tick() {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
}

If you do this you can then use it like any other React component:

import React from "react";
import Tick from "./core/Main.js";
//import logo from './logo.svg';
import "./App.css";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <div id="welcome">
          <Tick />
        </div>
      </header>
    </div>
  );
}

export default App;

If you want to stick to your original way of using tick as a function (e.g. if you have some special requirements) you need to actually call that function somewhere, preferably after the initial render of App, inside a useEffect:

import React from "react";
import tick from "./core/Main.js";
//import logo from './logo.svg';
import "./App.css";

function App() {
  React.useEffect(() => {
    tick();
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <div id="welcome"></div>
      </header>
    </div>
  );
}

export default App;
tudor.gergely
  • 4,800
  • 1
  • 16
  • 22