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.

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

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.