4

I was wondering if there is any way to manipulate a date returned from an API inside the react-table component?

For example, the timestamp comes back from the API formatted as such 2019-08-31 06:27:14 ... What I would like it to look like is something like Monday 8th of August 2005 03:12:46 PM

I am using the react-table component to render the table and the column i would like to manipulate is the Signup Date column.

Any help would be greatly appreciated.

columns={[
    {
        Header: "ID",
        accessor: "id",
        show: false
    },
    {
        Header: "Signup Date",
        accessor: "signup_date"
    }
]}
CodeSauce
  • 255
  • 3
  • 19
  • 39
  • If I understand it correctly, you just need a way to transform your timestamp? – Honza Sedloň Aug 31 '19 at 07:21
  • Is it possible there is some function that I can use in the `columns` section of the react-table to do it? – CodeSauce Aug 31 '19 at 07:25
  • Yes you can use a [function based accessor](https://github.com/tannerlinsley/react-table/issues/515) – HMR Aug 31 '19 at 07:26
  • 1
    Hey @HMR ... I tried using the example you showed, but im getting `Error: A column id is required if using a non-string accessor for column above.` ... It looks like it cant find `d.signup_date` ... Is there any chance you could show me an example? Im kind of new to all this – CodeSauce Aug 31 '19 at 07:43
  • 1
    Have you tried giving the cololum(s) a unique id property? – HMR Aug 31 '19 at 08:00
  • 1
    @HMR ... Oh that seems to have worked adding a unique ID ... Thank you – CodeSauce Aug 31 '19 at 08:07

1 Answers1

3

You can modify it like this:

columns : {[
    {
        Header:"Signup Date",
        accessor:"signup_date",
        //this is the func your looking for, it can retuen custom tableCell
        Cell : (props)=>{
            //props.value will contain your date
            //you can convert your date here
            const custom_date = 'custom_date'+props.value
            return <span>{custom_date}</span>
        }
    }
]}

As another solution, it might be a good idea to wrap your table inside a parent container that delivers modified data to table. sth like this:
container.js

componentDidMount(){
    const {data} = this.props;
    let tableData = []
    for(let me in data){
        let object = {
            //select and modify data from incoming server data
            date : 'fake date'
        }
        tableData.push(object)
    }
    this.setState({
        data : tableData
    })
}
render(){
    return(
        <React-Table
           //...settings
           data = {this.state.data}
        />
    )
}

hope this helps.

punjira
  • 818
  • 8
  • 21
  • You should use a `setState` in did mount instead of mutating props, mutating props is not a good idea. In render you can use `this.state` to pass as props to the react table. – HMR Aug 31 '19 at 08:06