Skip to content

Instantly share code, notes, and snippets.

@schmidsi
Created August 4, 2016 15:13
Show Gist options
  • Save schmidsi/b0aca8b85ba41466948beb3793bef120 to your computer and use it in GitHub Desktop.
Save schmidsi/b0aca8b85ba41466948beb3793bef120 to your computer and use it in GitHub Desktop.
A simple React SVG Clock Icon which can display a given time
// React imports
import React from 'react';
const Clock = (props) => {
const center = {
x: 15,
y: 15,
};
const lengths = {
hour: 9,
minutes: 12,
};
const floatingHour = (props.hours % 12) + (props.minutes / 60);
const angle = {
hour: 2.0 * Math.PI * floatingHour / 12.0,
minute: 2.0 * Math.PI * floatingHour,
};
return (
<svg viewBox="0 0 30 30" style={{ border: '2px solid black' }}>
<g id="hands">
<line
style={{ stroke: 'black', strokeWidth: 2 }}
x1={center.x}
y1={center.y}
x2={center.x + lengths.hour * Math.sin(angle.hour)}
y2={center.y - lengths.hour * Math.cos(angle.hour)}
/>
<line
style={{ stroke: 'black', strokeWidth: 2 }}
x1={center.x}
y1={center.y}
x2={center.x + lengths.minutes * Math.sin(angle.minute)}
y2={center.y - lengths.minutes * Math.cos(angle.minute)}
/>
</g>
</svg>
);
};
Clock.propTypes = {
hours: React.PropTypes.number,
minutes: React.PropTypes.number,
};
Clock.defaultProps = {
hours: 12,
minutes: 15,
};
export default Clock;
@schmidsi
Copy link
Author

schmidsi commented Aug 4, 2016

Thanks to Eric Bainville for the brilliant answer on Stackoverflow which helped me to keep a cool head while fighting with the according linear algebra stuff.

@matthiask
Copy link

Very nice! Esp. the use of SVG with React.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment