plotly 실행 예제

환경 구축

 npx create-react-app plotly 
 
 npm install react-plotly.js plotly.js
 
 npm start
 
 npx create-react-app simple-react-board --template typescript

App.js 파일에 아래 스크립트 입력

// App.js
import Plot from 'react-plotly.js';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Plot
          data={[
            {
              x: [1, 2, 3],
              y: [2, 6, 3],
              type: 'scatter',
              mode: 'lines+markers',
              marker: { color: 'red' },
            },
            { type: 'bar', x: [1, 2, 3], y: [2, 5, 3] },
          ]}
          layout={{ width: 320, height: 240, title: 'A Fancy Plot' }}
        />
      </header>
    </div>
  );
}

export default App;

MySQL 예제

sql 데이터를 미리 Import 해두자.

추가 패키지 설치

npm install mysql axios react-bootstrap bootstrap cors

npm run start

react-plotly/server/config/db.js 파일 생성

// db.js

var mysql = require('mysql');
const db = mysql.createPool({
    host : 'localhost',
    user : 'plotly',
    password : 'plotly',
    database : 'plotly',
    port: 3306,
});

module.exports = db;

react-plotly/server/server.js 파일 생성

// server.js

const express = require("express");
const app = express();
const PORT = process.env.PORT || 8000;
const db = require("./config/db");
// CORS 에러 방지
const cors = require("cors");
app.use(cors({ origin: "http://localhost:3000" })); //모든 접근 허용

app.get("/iris", (req, res) => {
  db.query(
    "SELECT `Sepal.Length` as sl, `Sepal.Width` as sw,`Petal.Length` as pl,  `Petal.Width` as pw , `Species` as sp  from iris;",
    (err, result) => {
      if (!err) {
        // console.log("db run");
        res.send({ result });
        // console.log(result);
      } else {
        console.log(err);
        res.send(err);
      }
    }
  );
});

app.listen(PORT, () => {
  console.log(`Server On : https://localhost:${PORT}/`);
});

실행은 node ./src/server/server.js로 실행

만약 DB에 접근되지 않는 경우 아래 명령어 실행

최신 MySQL DB는 caching_sha2_password 방식의 암호화를 사용하는데 인증을 위해 예전방식을 사용하려면 아래와 같이 mysql_native_password 변경해주어야한다.따라서 아래 명령어는 MYSQL DB의 모든 포트를 허용(%)하는 사용자인 plotly의 암호화 방식을 변경하겠다는 것이다.

React프로젝트(Node.js서버)와 Mysql연동
React프로젝트에 아래목록 작업이 모두 완료되었다면 이번엔 로컬DB mysql과 연결을 해보겠습니다. 웹서버구축 (참고페이지 링크) 서버-클라이언트 연결 (참고페이지 링크) Mysql이 설치되어있지 않다면 Mysql사이..

테이블 보여주기 예제

App.js에 아래 스크립트 입력

// App.js
import { Component } from "react";
import Table from "react-bootstrap/Table";
import Button from "react-bootstrap/Button";

/**
 * BoardList class
 */
class BoardList extends Component {
    /**
     * @return {Component} Component
     */
    render() {
        return (
            <div>
                <Table striped bordered hover>
                    <thead>
                        <tr>
                            <th>선택</th>
                            <th>번호</th>
                            <th>제목</th>
                            <th>작성자</th>
                            <th>작성일</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <input type="checkbox"></input>
                            </td>
                            <td>1</td>
                            <td>게시글1</td>
                            <td>artistJay</td>
                            <td>2022-03-19</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="checkbox"></input>
                            </td>
                            <td>2</td>
                            <td>게시글2</td>
                            <td>artistJay</td>
                            <td>2022-03-19</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="checkbox"></input>
                            </td>
                            <td>3</td>
                            <td>게시글2</td>
                            <td>artistJay</td>
                            <td>2022-03-19</td>
                        </tr>
                    </tbody>
                </Table>
                <Button variant="info">글쓰기</Button>
                <Button variant="secondary">수정하기</Button>
                <Button variant="danger">삭제하기</Button>
            </div>
        );
    }
}

export default BoardList;
[VSCode] React + nodejs + mySQL로 게시판 만들기 2편 - 게시판 UI 만들기
리액트 개발환경은 세팅했으니 이제 게시판 UI를 만들어보자. 게시판은 목록 조회, 글쓰기, 상세 조회, 수정하기, 삭제하기 기능만 만들고, 중간 상태 점검을 한 후에 추가 기능을 구현하겠다. 먼저, react-bootst..

만약 추가로 CORS 에러가 발생할 때 아래 링크를 참조하면 될 것 같다.

React + Express | CORS 설정하기
CORS개념은 이전 포스팅에서 다뤘으므로 생략하겠습니다. 프론트는 http://localhost:3000, 서버는 http://localhost:8000이라고 가정할 때, 프론트에서 axios.get(‘http://localhost:8000’)하게 되면 서로 다른 o

DB에 있는 BOARD 그리기

// App.js
import { Component } from "react";
import Axios from "axios";
import Table from "react-bootstrap/Table";
import Button from "react-bootstrap/Button";

const Iris = ({ sl, sw, pl, pw, sp }) => {
  return (
    <tr>
      <td>
        <input type="checkbox"></input>
      </td>
      <td>{sl}</td>
      <td>{sw}</td>
      <td>{pl}</td>
      <td>{pw}</td>
      <td>{sp}</td>
    </tr>
  );
};
/**
 * BoardList class
 */
class IrisList extends Component {
  state = {
    irisList: [],
  };
  getList = () => {
    Axios.get("http://localhost:8000/iris", {})
      .then((res) => {
        const { data } = res;
        this.setState({
          irisList: data,
        });
      })
      .catch((e) => {
        console.error(e);
      });
  };

  /**
   */
  componentDidMount() {
    this.getList();
  }
  /**
   * @return {Component} Component
   */
  render() {
    // eslint-disable-next-line
    const { irisList } = this.state;
    // console.log(irisList.result);
    return (
      <div>
        <Table striped bordered hover>
          <thead>
            <tr>
              <th>Sepal.Length</th>
              <th>Sepal.Width</th>
              <th>Petal.Length</th>
              <th>Petal.Width</th>
              <th>Species</th>
            </tr>
          </thead>
          <tbody>
            {irisList.result &&
              irisList.result.map((d) => {
                return (
                  <Iris sl={d.sl} sw={d.sw} pl={d.pl} pw={d.pw} sp={d.sp} />
                );
              })}
          </tbody>
        </Table>
        <Button variant="info">글쓰기</Button>
        <Button variant="secondary">수정하기</Button>
        <Button variant="danger">삭제하기</Button>
      </div>
    );
  }
}

export default IrisList;

DB에 있는 IRIS 그림그리기[진행예정]

DB에 아래 데이터를 Import 해오자.