Functions are a great way to reuse code when writing in vanilla Javascript. It can save you a lot of time and makes your code cleaner and easier to read. In React, however, you write your code as components which can also be reused by passing in props. I'll assume you've read the hundreds of blog posts on how to create-react-app
so let's skip that part altogether and just get started!
We'll be creating two simple button components that will console.log()
"Hello" and the other will log "Shia LaBeouf", naturally. In our /src
folder let's create a subfolder called "components" and create our Button component. Your file structure should look like this:
Let's make that component a functional component. React Hooks have been the hot new rage past year so I suggest you Google it if you haven't heard of it. Here's what our Button component looks like now:
import React from "react";
const Button = () => <button>something</button>;
export default Button;
Whoa.
Now, let's go into our App.js file and replace the starter template that comes with create-react-app
with our two Button components. Don't forget to import it up at the top!
import React from "react";
import "./App.css";
import Button from "./components/Button";
function App() {
return (
<>
<Button />
<Button />
</>
);
}
export default App;
Running npm start
in your terminal will bring our lovely website to life. Just two buttons that say "something" in the upper left corner against a white background. Hey, I'm teaching you about reusable components, not how to style.
So, as it stands, we have two buttons that look the exact same and do the exact same thing (nothing). If you've been paying any sort of attention, to make the same button do different things you need to pass it props from its parent. In this case, it's App.js.
Let's differentiate between the two "something" buttons by passing it label props:
// App.js
<Button label="Hello" />
<Button label="Shia LaBeouf" />
And by receiving the prop as an argument and then calling on those props:
// Button.js
const Button = props => <button>{props.label}</button>;
Now take a look at your website. One button says "Hello" and the other says "Shia", naturally. I think you can see where I'm going with this "props" stuff.
Let's add our onClick
handlers which will execute a function to log some text into our console:
// Button.js
const Button = props =>
<button onClick={props.log}>
{props.label}
</button>;
// App.js
const log = e => {
console.log(e.target.textContent);
};
function App() {
return (
<>
<Button label="Hello" log={log} />
<Button label="Shia LaBeouf" log={log} />
</>
);
}
Now take a look at your console when you click on one of the buttons. Whoa. We just used the same Button component while naming it two different things and logging two different things. This is the power of React!
Top comments (2)
Awesome
Thank you very much!