0

I have component with function dateBuilder inside, which I use to get the current date.

import React from 'react';
import './WeatherBox.css'
import { Icons } from '../../icons';


const dateBuilder = (d) => {
    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    let day = days[d.getDay()];
    let date = d.getDate();
    let month = months[d.getMonth()];
    let year = d.getFullYear();

    return `${day} ${date} ${month} ${year}`
}

const WeatherBox = ({currentWeatherResult}) => {
        return (
            <div className="locationDate">
                <span>{currentWeatherResult.location}</span>
                <span>{dateBuilder(new Date())}</span>
                <span>{currentWeatherResult.temp}°C</span>
                <img src={Icons[currentWeatherResult.sky]} alt={Icons[currentWeatherResult.sky]} />   
            </div>
        )

}

export default WeatherBox;

So, if I want to move this function to another direction as a helper, how can I export it to any component I want to?

1 Answer 1

1

DateBuilder is pure javascript function, no need to export it as component. You can export it as javascript function.

const dateBuilder = (d) => {
    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    let day = days[d.getDay()];
    let date = d.getDate();
    let month = months[d.getMonth()];
    let year = d.getFullYear();

    return `${day} ${date} ${month} ${year}`
}

export default dateBuilder;

You can use it in the following way

import React from 'react';
import './WeatherBox.css'
import { Icons } from '../../icons';
import dateBuilder from './dateBuilder';

const WeatherBox = ({currentWeatherResult}) => {
        return (
            <div className="locationDate">
                <span>{currentWeatherResult.location}</span>
                <span>{dateBuilder(new Date())}</span>
                <span>{currentWeatherResult.temp}°C</span>
                <img src={Icons[currentWeatherResult.sky]} alt={Icons[currentWeatherResult.sky]} />   
            </div>
        )

}

export default WeatherBox;

To addition to your question, you are trying to manually format the date. There are some good packages available in js like moment to easily format date.

You can refer this or this for more info about moment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.