Home > database >  Adding component that runs a simple js script to create-react-app app
Adding component that runs a simple js script to create-react-app app

Time:10-18

Hi This seems like something that should be simple but no matter how many searches I do i can't seem to find a clear answer or i'm just fundamentally misunderstanding something. I want to add a simple component.

I have a simple react app here is the app.js

import logo from './logo.svg';
import './App.css';
import fortune from './fortune.js' ;

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Wowsersssss
        </p>
      
      <button onclick="myFortune()">Fortune</button>
      </header>
    </div>
  );
}

export default App;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

and a simple component that I am importing

import React from 'react';
import ReactDOM from 'react-dom';
function fortune() {
  const message = () => {
    alert("Hello");
  }

  return (
    <button onClick={message}>Click Here</button>
  );
}

ReactDOM.render(<fortune />, document.getElementById('root'));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How do I now insert that into the app.js?

I'd really appreciate if someone could show me where to add it in.

Thanks!

CodePudding user response:

You seem to have the code the wrong way round. App should be the component that's attached to the main react element in the DOM (generally), and then you import new components. Also, new components should have names written in Pascal Case otherwise you'll get errors.

So here I've created a MyFortune component, and it gets imported into App.

function MyFortune() {

  function message() {
    console.log('Hello');
  }

  return (
    <button
      onClick={message}
    >Click Here
    </button>
  );

}

function App() {
  return (
    <div>
      <header>
        <p>Wowsersssss</p>
        <MyFortune />
      </header>
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You need to export the component itself so that you can Import it. You need to Capitalize your Function Name as well for the component.

Function Fortune(){ return( I am a button ) }

export default Fortune

//////////////

Import Fortune from './Fortune' //Assuming they're in the same folder level

//You can Display it by Declaring it inside the <> just like meta tags do

  • Related