Skip to content

Commit 411c3d1

Browse files
AnenthCompuIves
authored andcommitted
Refactor Search box (codesandbox#255)
* Refactor Search box - Remove the use of state as the query keyword is required only after user hits enter - Move the component to simple function component * Fix page getting reload on search
1 parent fb8f8a6 commit 411c3d1

File tree

1 file changed

+23
-31
lines changed

1 file changed

+23
-31
lines changed

src/app/components/HeaderSearchBar.js

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -40,44 +40,36 @@ const StyledSearchIcon = styled(SearchIcon)`
4040
color: rgba(255, 255, 255, 0.7);
4141
`;
4242

43-
const StyledSearchButton = styled.a`
43+
const StyledSearchButton = styled.button`
4444
position: absolute;
45-
right: 0.5em;
45+
right: 0;
4646
top: 50%;
47+
padding: 0.35em 0.5em;
4748
transform: translate(0, -50%);
4849
z-index: 20;
50+
background: transparent;
51+
outline: none;
52+
border: none;
53+
cursor: pointer;
4954
`;
5055

51-
export default class HeaderSearchBar extends React.PureComponent {
52-
state = {
53-
query: '',
56+
const HeaderSearchBar = () => {
57+
const handleFormSubmit = (e: KeyboardEvent) => {
58+
e.preventDefault();
59+
const searchQuery = e.target.elements.q.value;
60+
history.push(searchUrl(searchQuery));
5461
};
5562

56-
handleChange = e => {
57-
this.setState({ query: e.target.value });
58-
};
59-
60-
handleKeyUp = (e: KeyboardEvent) => {
61-
if (e.keyCode === 13) {
62-
// Enter
63-
history.push(searchUrl(this.state.query));
64-
}
65-
};
66-
67-
render() {
68-
const currentSearchUrl = searchUrl(this.state.query);
69-
70-
return (
71-
<Container>
72-
<Input
73-
onChange={this.handleChange}
74-
placeholder="Search sandboxes"
75-
onKeyUp={this.handleKeyUp}
76-
/>
77-
<StyledSearchButton href={currentSearchUrl}>
63+
return (
64+
<Container>
65+
<form onSubmit={handleFormSubmit}>
66+
<Input name="q" placeholder="Search sandboxes" />
67+
<StyledSearchButton>
7868
<StyledSearchIcon />
7969
</StyledSearchButton>
80-
</Container>
81-
);
82-
}
83-
}
70+
</form>
71+
</Container>
72+
);
73+
};
74+
75+
export default HeaderSearchBar;

0 commit comments

Comments
 (0)