Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created May 10, 2025 13:55
Show Gist options
  • Save sunmeat/5cbbf0d68d2cf925d3985af34b191994 to your computer and use it in GitHub Desktop.
Save sunmeat/5cbbf0d68d2cf925d3985af34b191994 to your computer and use it in GitHub Desktop.
state simple example
import React, {useState} from 'react'
import './App.css'
const getRandomColor = () => {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function MyButton() {
const [color, setColor] = useState('blue'); // color - состояние, setColor - функция для его изменения
// деструктурирующее присваивание, useState возвращает массив с двумя элементами
return (
<button style={{ backgroundColor: color }} onClick={() => setColor(getRandomColor())}>
Нажми меня
</button>
);
}
function BorderedButton() {
return (
<div className="bordered">
<MyButton />
</div>
);
}
export class MyHeader extends React.Component {
render() {
return <h1>Hello</h1>
}
}
function App() {
return (
<>
<MyButton/>
<MyHeader/>
<BorderedButton />
</>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment