Hi guys,
I’m having a hard time figuring out why my code doesn’t work.
What I am trying to do is to concatenate inputVal
in this request let myRequest = "https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&srsearch="+ this.state.inputVal + "&format=json";
In order to only change the srsearch
part of the request according to what the user has entered in the input field
.
However, when using this method, it does not recognize the srsearch
property and throws an error telling me that it needs srsearch
property to work.
I’ve tried using this.inputVal
instead, by doing that, the property is recognized, but undefined
is returned…
Here is my component:
import React from 'react';
import styled from 'styled-components';
const InputDiv = styled.div `
text-align: center;
margin-top: 1em;
`
const StyledParagraph = styled.p `
color: white;
text-align: center;
margin-top: 1em;
`
const StyledInput = styled.input.attrs({
type: "text"
})`
margin: auto;
border: 4px solid orange;
background-color: transparent;
border-radius: 25px;
color: white;
padding: 3px 1em;
&:focus {
outline: 5px white;
}
`;
export default class SearchArticle extends React.Component {
constructor(props) {
super(props);
this.state = {
inputVal: "",
articles: []
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
let myRequest = "https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&srsearch="+ this.state.inputVal + "&format=json";
fetch(myRequest)
.then(res => res.json())
.then((data) => {
this.setState({ articles: data })
})
.catch(console.log)
}
handleChange(e) {
let targetEvent = e.target.value;
this.setState({
inputVal: targetEvent
})
}
handleSubmit(e) {
e.preventDefault();
console.log(this.state.inputVal);
console.log(this.state.articles);
}
render() {
return (
<InputDiv>
<form onSubmit={this.handleSubmit}>
<StyledInput onChange={this.handleChange} />
</form>
<StyledParagraph>Type something to search</StyledParagraph>
</InputDiv>
);
}
}
Can anyone help me understand what I am doing wrong please?
I am fairly new to manipulating React State and using Lifecycle methods… And I feel like I did not understand properly how this works…
Thanks in advance