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;
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'));
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!
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>
);
}
// export default MyFortune;
// import MyFortune from './MyFortune';
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>
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.
import React from 'react'
function Fortune(){
function clicked(){
console.log('clicked')
}
return(
<button onClick={clicked}>I am a button</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
<Fortune />
You can add a onlick function towards the component but the function must be above the return statement if complex or can be a one-liner code on the JSX return section. Take note that React uses pascal Case on these functions when Called like onClick not onclick, className not className .