Skip to content

Latest commit

 

History

History
148 lines (116 loc) · 2.51 KB

react-examples.md

File metadata and controls

148 lines (116 loc) · 2.51 KB

Kodexempel från teoridelen

Att bygga en reactkomponent

//MyComponent.js
import React from "react";

// const MyComponent = ({ title, content }) => {...
const MyComponent = (props) => {
  const { title, content } = props;
  return (
    <div>
      <h2>{title}</h2>
      <hr />
      <p>{content}</p>
      <footer>Copyright &copy; React 2018</footer>
    </div>
  );
};

export default MyComponent;

Konsumera komponent

//MyComponent.js
import React from "react";
import Hello from "./Hello";

const MyComponent = () => {
  return (
    <div className="container">
      <Hello title="hello opkoko" content="React is awesome!" />
    </div>
  );
};

export default MyComponent;

Component state

import React, { useState } from "react";

const ComponentWithState = () => {
  const [active, setActive] = useState(true);

  handleClick = (e) => {
    setActive(!active);
  };

  const buttonText = active ? "On" : "Off";
  return (
    <div className="ComponentWithState">
      <p>Click the button!</p>
      <button onClick={handleClick}>Click me!</button>
      <p>{buttonText}</p>
    </div>
  );
};

export default ComponentWithState;

useEffect

import React, { useEffect, useState } from "react";

const UseEffectComponent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

export default ComponentWithState;

User events

import React from "react";

const UserEventComponent = () => {
  const [input, setInput] = useState("");

  const handleOnChange = (event) => {
    const text = event.target.value;
    setInput(text);
  };

  return <input type="text" onChange={handleOnChange} />;
};

export default UserEventComponent;

Map + Keys

import React from "react";

const ComponentWithList = ({ items }) => {
  return (
    <>
      <h1>Awesome people list</h1>
      <ul>
        {items.map((item) => {
          return <li key={item.id}>{item.name}</li>;
        })}
      </ul>
    </>
  );
};

export default ComponentWithList;
//...konsumera ComponentWithList

const items = [
  {
    id: 1,
    name: "Anton",
  },
  {
    id: 2,
    name: "Mathias",
  },
];
<ComponentWithList items={items} />;