Skip to content

Instantly share code, notes, and snippets.

@Bwogi
Last active December 11, 2021 23:08
Show Gist options
  • Select an option

  • Save Bwogi/9c350eb46ce02d8fefb8b2f7482a052c to your computer and use it in GitHub Desktop.

Select an option

Save Bwogi/9c350eb46ce02d8fefb8b2f7482a052c to your computer and use it in GitHub Desktop.
This is how props work in React ;) and styles

Props & component styles Explained

example 1 (header.js)

import React from 'react';

const Header = ({ title, year, message }) => {
	return (
		<header>
			<h3 style={headerStyles}>
				{title} {year} - {message}
			</h3>
		</header>
	);
};
Header.defaultProps = {
	title: 'Task tracker',
	year: '2021',
	message: 'This task tracker is fantastic',
};

const headerStyles = {
	color: 'red',
	backgroundColor: 'black',
};

export default Header;

example 1 (App.js)

import React from 'react';
import Counter from './components/Counter';
import './App.css';
import Header from './components/Header';
import Footer from './components/Footer';

const App = () => {
	return (
		<div className='container'>
			<Header />
			<Counter max={5} />
			<Footer />
		</div>
	);
};

export default App;

example 2(components/Button/index.js)

import React from 'react';

const Button = ({ text, color }) => {
	return (
		<button style={{ backgroundColor: color }} className='btn'>
			{text}
		</button>
	);
};

export default Button;

example 2(/components/Header/index.js)

import Button from '../Button';

const Header = ({ title }) => {
	return (
		<header className='header'>
			<h1>{title}</h1>
			<Button color='green' text='Add' />
			<Button color='red' text='delete' />
			<Button color='orange' text='check' />
		</header>
	);
};
Header.defaultProps = {
	title: 'Task Tracker',
};

export default Header;

example 3

function App() {
  return <Child somename="Kawuma" ></Child>
}

function Child(props) {
  return <div>{props.somename}</div>
}

The code above would render a <div> that contains "Kawuma"! That's right—because components are functions, we can pass in any type of argument we want. Rather than passing it in through parentheses, though, you need to pass them in as attributes on the component in JSX. This is JSX, so you can name those attributes whatever you want, without the need for the data- prefix. Then within the Child component, props is nothing more than the name of the parameter, which you could change to be whatever you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment