Reputation: 423
I would like to handle an onClick event on a DIV (in REACT JS) which is a styled-component actually. But this not works at all.
Here is the pseudo code of my build-up:
<Styled_DIV onClick={() => props.method(props.arg)}>
<AnotherElement/>
...
</Styled_DIV>
My workaround which works properly:
<div onClick={() => props.method(props.arg)}>
<Styled_DIV}>
<AnotherElement/>
...
</Styled_DIV>
</div>
So, my question is: what's the official / best way to handle an onClick event on a styled-component div without wrapper div?
Thanks in advance :)
Upvotes: 5
Views: 23056
Reputation: 352
You can attach the event handlers directly without wrapper div.
index.js
import React from "react";
import { render } from "react-dom";
import Wrapper from "./Wrapper";
const App = () => <Wrapper onClick={() => alert("Hello")}>Hello</Wrapper>;
render(<App />, document.getElementById("root"));
Wrapper.js:
import styled from "styled-components";
export default styled.button`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
Code Link: https://codesandbox.io/s/styled-components-d731y?fontsize=14&hidenavigation=1&theme=dark
You also have other options like typestyle https://github.com/typestyle/typestyle, Styletron https://github.com/styletron/styletron and others as well which can be used with react.
Upvotes: 11
Reputation: 27
because you don't create the Styled_DIV component that'll render an tag
just add this code
const Styled_DIV = styled.div``
Upvotes: -2