React is not a framework , it’s a javascript library developed by facebook.
Before
start the Project , First and forthwith I want to say if you have not already
installed react then first you have to install it. For this you need to first
download and install node and follow the commands.
To
Install react-app Node Package :
npminstall
-g create-react-app
Create
your react app
npx create-react-app app-name
This
will create a sample ready to edit app that we need to edit and use. After this
command you will see your app folder is got created, inside this there will be many
folders but you have to focus on only two folders such as public and source folder.
So this all about installation of ReactJS and creating first app.
Now we will start with how to fetch and show url data
in our first react app.
Fetch URL
In App.js file of src folder, Create Class Component,
to define a React Component class , you need to extend React.Component :
Constructor used to initialize object’s state in the class . it automatically gets called when object of class is created. You have to define constructor before the compenent mounted. When implementing the constructor for React.Component subclass, you should call super() before any other statement. You should not call setState() in the constructor but you can assign the initial state to this.state directly in constructor and I assign value items:[ ] as an empty array .
Yes ! now we
are ready to set any value or URL data in an empty array with the help of setState()
method.
componentDidMount() is invoked immediately after a component is
mounted means component has been loaded to the DOM.
componentDidMount() {let url = "sample.json";fetch(url) //fetch url.then(result => result.json()) //promise.then(json => {this.setState({ // set state data :result as json dataitems: json,})})}
In this code, We want to fetch url data or API data so we call fetch() method with url
or you can directly pass url as a string
fetch("sample.json")
you can fetch
any url , I created a simple json file in public folder which has user data in
json format and we are fetching data from this file. In real time this will be
an actual url of API.
Now
you can set this json data to the items array with the help of setState()
method.
So
it’s too easy to fetch url. Right?
Last
step is render the data with map method. You can see code below:
Never forget to export this component
entire
code are shown below :
index.html
Index.js
App.js
For run this app, navigate to the app folder and use command:
npm
start
you will see the output in your browser.
check this complete code
thanks
for reading . try this simple app and free to comment your questions and
feedback.
Comments
Post a Comment