I'm new to React so please bear with me.
I'm using react-data-table-component to render a Datatable. I want to render it only after the user has submitted the form and has gathered the necessary data to query my backend.
Here is my code working code:
const Table = ({ data }) => {
const columns = [
{
name: 'Date',
selector: (row) => row.created_at,
format: (row) => moment(row.created_at).format(),
}
]
return <DataTable columns={columns} data={data} />;
};
export default Table;
function App() {
const [someString, setSomeString] = useState('');
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
const [data, setData] = useState({});
const handleSubmit = (e) => {
e.preventDefault();
const dataSubmit = { someString, startDate, endDate };
fetch('/table', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(dataSubmit),
})
.then((res) => res.json())
.then((data) => {
setData(data);
});
};
return (
<div className='App'> <Table data={data} /> </div>
);
}
export default App;
I want to render my Table component only when the useState
object for data
is not empty and not display my table if the data
object is empty. I'm having a hard time understanding how to render on a conditional basis in code. I'm aware that I'm not showing my date and form components in my code but hoping this is enough detail to get the question across. I'll be happy to add more information if needed. Any help will be greatly appreciated, thank you.
I guess you can simply add a check as follows:
const Table = ({ data }) => {
const columns = [
{
name: 'Date',
selector: (row) => row.created_at,
format: (row) => moment(row.created_at).format(),
}
]
return data && <DataTable columns={columns} data={data} />; //UPDATE THIS LINE
};
export default Table;
In case of empty object you can add a check like data && Object.keys(data).length !== 0
.
I hope your data is not empty array, other wise you can change it to data && data.length>0 && <DataTable columns={columns} data={data} />;