You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ReactJS中基于用户表单输入添加柱状图

Add a Bar Chart to Your React Form Submission

Absolutely! Let's get that bar chart up and running for your submitted form data. I'll use Recharts—a lightweight, easy-to-use charting library built specifically for React—to make this straightforward. Here's how to modify your code step by step:

Step 1: Install Recharts

First, add the library to your project:

npm install recharts
# or
yarn add recharts

Step 2: Update Your Component Code

I've fixed a couple of small issues in your original code (like missing name attributes on inputs, which were breaking your state updates) and added the chart logic:

import React, { useState } from 'react';
// Import required Rechart components
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';

const Multipleinput = () => {
  const [userInfo, setUserInfo] = useState({ Name: "", MonthDays: "", Availablefordays: "" });
  const [records, SetRecords] = useState([]);

  const handleInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setUserInfo({ ...userInfo, [name]: value })
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    // Convert numeric values from string to number (critical for charting)
    const newRecord = {
      ...userInfo,
      MonthDays: Number(userInfo.MonthDays),
      Availablefordays: Number(userInfo.Availablefordays),
      id: new Date().getTime().toString()
    }
    SetRecords([...records, newRecord]);
    setUserInfo({ Name: "", MonthDays: "", Availablefordays: "" });
  }

  return (
    <div style={{ padding: '2rem' }}>
      <form onSubmit={handleSubmit} style={{ marginBottom: '2rem' }}>
        <div style={{ marginBottom: '1rem' }}>
          <label htmlFor="Name">Name</label>
          {/* Add name attribute to match state keys */}
          <input 
            type="text" 
            name="Name"
            value={userInfo.Name} 
            onChange={handleInput}
            style={{ marginLeft: '0.5rem' }}
          />
        </div>
        <div style={{ marginBottom: '1rem' }}>
          <label htmlFor="MonthDays">Month Days</label>
          <input 
            type="number" 
            name="MonthDays"
            value={userInfo.MonthDays} 
            onChange={handleInput}
            style={{ marginLeft: '0.5rem' }}
          />
        </div>
        <div style={{ marginBottom: '1rem' }}>
          <label htmlFor="Availablefordays">Available for days</label>
          <input 
            type="number" 
            name="Availablefordays"
            value={userInfo.Availablefordays} 
            onChange={handleInput}
            style={{ marginLeft: '0.5rem' }}
          />
        </div>
        <button type="submit" >Save User</button>
      </form>

      {/* Render chart only when there are records */}
      {records.length > 0 && (
        <BarChart
          width={600}
          height={300}
          data={records}
          margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="Name" /> {/* Use Name as x-axis labels */}
          <YAxis />
          <Tooltip />
          <Legend />
          {/* Bar for MonthDays data */}
          <Bar dataKey="MonthDays" fill="#8884d8" />
          {/* Bar for Availablefordays data */}
          <Bar dataKey="Availablefordays" fill="#82ca9d" />
        </BarChart>
      )}
    </div>
  )
}

export default Multipleinput;

Key Changes Explained:

  • Fixed Input name Attributes: Your handleInput function relies on e.target.name to update the state—without these, your form values weren't saving correctly.
  • Converted Numeric Values: Inputs return string values by default, so we convert MonthDays and Availablefordays to numbers before saving to records (charts need numeric data).
  • Conditional Chart Rendering: The chart only shows up once you've submitted at least one record.
  • Chart Configuration:
    • XAxis dataKey="Name" uses the submitted names as labels on the horizontal axis.
    • Two Bar components map to your MonthDays and Availablefordays data, each with a unique color.
    • Added basic styling (padding, margins) to make the layout cleaner.

How It Works:

Every time you submit the form, a new record is added to the records state array. The Recharts component automatically re-renders with the updated data, showing a side-by-side bar comparison for each user's Month Days and Available Days.

内容的提问来源于stack exchange,提问作者Prateek Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:42:50