I’ve written a ReactJS app, where I have list of data (JSON data) showed in table view. I’ve used "react-data-table-component" for that. It works fine, right now whenever the app launches it fetches and displays the data in table UI. But, I want to display this JSON data only when user clicks on "Submit" button <button type="submit">Submit</button>
. I have pasted the code below. I am not able to use either <button onClick
to display the data using DataTable or not able to achieve this. Could you please help me how can I display data only clicking on Submit button?
import DataTable from "react-data-table-component"
import { useState, useEffect } from "react"
function App() {
const [data, setData] = useState([])
const [loading, setLoading] = useState(false)
const [perPage, setPerPage] = useState(10)
const columns = [
{
name: "In Market Date",
selector: (row) => row.userId,
width: "120px",
wrap: true
},
{
name: "Topic/Title",
selector: (row) => row.title,
wrap: true
},
{
name: "Sl Number",
selector: (row) => row.title,
wrap: true
},
{
name: "Document ID",
selector: (row) => row.title,
wrap: true
},
{
name: "Meeting Contact",
selector: (row) => row.title,
wrap: true
},
{
name: "Reference",
selector: (row) => (row.completed ? "Yes" : "No"),
wrap: true
},
]
useEffect(() => {
fetchTableData()
}, [])
async function fetchTableData() {
setLoading(true)
const response = await fetch('https://jsonplaceholder.typicode.com/todos')
const users = await response.json()
setData(users)
setLoading(false)
}
return (
<div className="wrapper">
<h1> User info </h1>
<form>
<fieldset>
<label>
<p>User Name:</p>
<input name="name" />
</label>
<label>
<p>DM Number:</p>
<input name="number" />
</label>
<label>
<p>Document ID:</p>
<input name="docnumber" />
</label>
</fieldset>
<button type="submit">Submit</button>
</form>
<DataTable
//title="Data"
columns={columns}
data={data}
progressPending={loading}
pagination
/>
</div>
)
}
export default App;
2
Answers
You could create a variable to keep track of the submit button
Then create a function that handles the submit
An then render the table only if submit == true
Also, you need to create the submit function
Here is the code with the changes
Please let me know if this worked for you
There many ways to do that. One simple solution is to add another
useState
for keeping a show/hide bool flag, false by default. When the submit button is clicked, just to set the flag to true, and also pass table data based on the flag value. Here is an example I made: https://codesandbox.io/s/interesting-violet-rg7y6s?file=/src/App.jsA better way to do the whole thing could be using "react-query", which allows you not to fetch data by default, but fetch data manually when the submit button is clicked.