I am new to React Framework. I am having trouble exporting a usestate value queryCity to another js file.
I have a code React index.js code like below:
import React, { useState } from "react";
const Home = () => {
const [queryCity, setQueryCity] = useState("New York");
return(
<div>
<input
type="text"
className="search-city"
placeholder="New York "
value={queryCity}
onChange={(e) => setQueryCity(e.target.value)}
/>
</div>
);
};
export default Home ;
Another file called 'Search.js' needs the queryCity from Home module.
I have tried createContext. But the Search.js is not the child component of Home
Because globalCity is scoped to the Home component, you will not have access to it in a parent scope.
If you want to access globalCity in another file, move it out of the Home component and into the parent scope and also export it.
import React, { useState } from "react";
export const globalCity = "New York";
const Home = () => {
...
Related
i have been trying to implement a context api solution since i want to use children states(data) in my app.js without lifting up the states. anyways i have tried to implement it a context api soloution to by doing the following :
i created a folder names context and then created Context.js
the code is as follows:
mport { createContext,useState } from "react";
export const Mycontext = createContext()
const Context = ({children}) =>{
const [post, setPost] = useState([])
return(
<Mycontext.Provider value={[post,setPost]}>
{children}
</Mycontext.Provider>
)
}
export default Context
i wrapped the index.js file with the Provider wrapper as follows:
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import Context from './context/Context';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Context>
<App />
</Context>
);
my main goal for now is to use useState hook data or states so i can use them in higher up comonents , in this case i want my post.js file to change usestate data in context so i can then use that data to post something in App.js using a container component that takes value as a props
i will post the both post.js and container.js and app.js below
import React,{useContext,useState,useEffect,useRef} from 'react'
import '../HomeMainStyling/HomeStyling.css'
import Tweets from './Tweets'
import Context from '../../context/Context'
function Tweet() {
const tw = useRef('')
const {post,setPost} = useContext(Context);
useEffect(() => {
if (post.length) console.log(post);
}, [post]);
function PostNow(event){
event.preventDefault();
setPost((oldpost) => [tw.current.value,...oldpost]);
}
return (
<div className="tweetcontainer">
<textarea ref={tw} className="tweetinfo"></textarea>
<button className="postIt" onClick={PostNow}>tweet</button>
</div>
)
}
export default Tweet
//
the container is the following:
import React from 'react'
import '../HomeMainStyling/HomeStyling.css'
function Tweets({value}) {
return (
<h2>{value}</h2>
)
}
export default Tweets
App.js:
import Tweet from './Center/HomeMain/Tweet';
import Tweets from './Center/HomeMain/Tweets';
import { useContext,useState } from 'react';
import Context from './context/Context';
function App() {
const {post,setPost} = useContext(Context);
return (
<div className="App">
<Tweet/>
<Tweets value={post}/>
</div>
);
}
export default App;
the app should in principle post 1 h1 element for every click in Tweet components
The useContext hook takes the context you created using createContext() as a parameter, but you are passing a custom component to it, so try:
import { Mycontext } from './context/Context';
const [post, setPost] = useContext(Mycontext)
<Mycontext.Provider value={[post,setPost]}>
this is wrong you ahve to write
<Mycontext.Provider value={{post,setPost}}>
I am learning React by making a motor cycle spec searching web application, and I am trying to import fetched data into makePicker.jsx to essentially make a drop down menu with those data.
However I am getting an error message saying:
Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
I am not sure what applies to my situation. Can you see why?
makePicker.jsx
import React, {useState, useEffect} from 'react';
import {NativeSelect, FormControl} from '#material-ui/core';
import styles from './makePicker.module.css';
import { makeList } from '../../api';
const MakePicker = ()=>{
const [fetchedMakes, setFetchedMakes] = useState([]);
useEffect(()=>{
const fetchAPI = async()=>{
setFetchedMakes(await makeList());
}
fetchAPI();
},[])
return (
<h1>makePicker</h1>
);
}
export default MakePicker;
App.js
import logo from './logo.svg';
import './App.css';
import {fetchData, makeList} from './api/index';
import React, {Component} from 'react';
import MakePicker from './components/makePicker/makePicker';
class App extends React.Component{
state = {
data:[],
makes:[],
}
async componentDidMount(){
// const fetchedData = await fetchData();
const fetchedMakeList = await makeList();
this.setState({makes:fetchedMakeList});
}
render(){
return (
<div className="App">
<header className="App-header">
{MakePicker()};
<h1>Some line-ups from YAMAHA</h1>
{this.state.makes.map(make=>{
return <p>{make.name}</p>
})}
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Open React
</a>
</header>
</div>
);
}
}
export default App;
Please let me know if need more information from my project.
According to your code in App.jsx and following the naming convention of React's component, you should import it with the first-capitalized-letter name like below
import MakePicker from './components/makePicker/makePicker';
You're also calling {makePicker()}; which is not a proper way for component rendering. You should modify it to
<MakePicker/>
Full possible change can be
import logo from './logo.svg';
import './App.css';
import {fetchData, makeList} from './api/index';
import React, {Component} from 'react';
import MakePicker from './components/makePicker/makePicker';
class App extends React.Component{
state = {
data:[],
makes:[],
}
async componentDidMount(){
// const fetchedData = await fetchData();
const fetchedMakeList = await makeList();
this.setState({makes:fetchedMakeList});
}
render(){
return (
<div className="App">
<header className="App-header">
<MakePicker/>
<h1>Some line-ups from YAMAHA</h1>
{this.state.makes.map(make=>{
return <p>{make.name}</p>
})}
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Open React
</a>
</header>
</div>
);
}
}
export default App;
To elaborate more why you get this error
Invalid hook call. Hooks can only be called inside of the body of a function component.
When you call makePicker(), it's actually triggering a Javascript's function (not React's component as you expected), but useEffect is only available in React's components. That's why when you try to run code, the compiler is thinking makePicker is calling useEffect invalidly.
Their is a problem lies on your useEffect
update the code like this and try it out:
const fetchAPI = async()=>{
const res = await makeList().then((data) => {
setFetchedMakes(data)
}).catch((err) => console.log(err))
}
useEffect(()=>{
fetchAPI();
},[])
here i placed the asynchronous function outside of the useEffect
Also make MakePicker as an JSX element like this: <MakePicker />
In the below code I want to pass name from Person.js to App.js as prop.But I can't understand how to do it.If you can please explain me how to do that.
App.js
import { useState,useEffect } from 'react';
// import Person from './Person'
function App(props) {
const [greet, setGreeet] = useState("");
return (
<div className="App">
<h1> Good {greet} </h1>
</div>
);
}
export default App;
Person.js
import React from 'react';
import App from './App'
export default function Person (){
const name="Jenifer"
return(
<div></div>
);
}
passing name as prop from person.js(Parent Component) to App.js(Child Component)
Person.js
import React from 'react';
import App from './App'
export default function Person (){
const name="Jenifer"
return(
<div>
<App name={name}/>
</div>
);
}
App.js
import { useState,useEffect } from 'react';
// import Person from './Person'
function App(props) {
const [greet, setGreeet] = useState("");
return (
<div className="App">
<h1> Good Morning {props.name} </h1> // Good Morning Jenifer
</div>
);
}
export default App;
checkout this blog post Passing props between components
I think you are asking for how to pass data from child to parent.
You have to pass a method from App to Person.
And call the method from Person component.
Also please see the docs
https://reactjs.org/docs/lifting-state-up.html
function Person (props){
const {setNameToApp} = props;
const name = "Jennifer";
// this useEffect is called when the component mounts for the first time
React.useEffect(()=>{
setNameToApp(name);
},[])
// I have also shown how to use button to change the greet state in the app.
return (
<div>
<button onClick={()=>{setNameToApp("name when I pressbutton")}}> Set Name </button>
</div>)
}
function App(props) {
const [greet, setGreet] = React.useState("");
// pass setGreet function to components which can call this and change the state of the greet
return (
<div>
<h1> Good {greet} </h1>
<Person setNameToApp = {setGreet} />
</div>
);
}
Finally I found the reason for this.This happened because I tried to pass data from my child class to parent class.It is impossible to do so.
I am trying to get a search bar to display on my main app in React. To do this I have created a new component called searchBox to be used later and therefore I can't just directly app the input to my App.js file.
My code for my App.JS file looks like :
import React, { Component } from 'react';
import CardList from './CardList';
import searchBox from './searchBox';
import { robots } from './robots';
const App = () => {
return (
<div>
<h1> Contacts </h1>
<searchBox />
<CardList robots={robots} />
</div>
)
}
export default App;
My searchbox.js file looks like :
import React from 'react';
const searchBox = () => {
return(
<input type='search' placeholder='search contacts' />
);
}
export default searchBox;
The header is displaying but the searchbox is not. I have the file save in the src folder as searchBox so I don't think the issue is to do with saving the file in the wrong location.
User defined components must be capitalized.
https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
Can you capitalize S in your searchBox? React expects component names to start with capital letter.
I'm teaching myself React-Native and I came across this strange roadblock. Inside my App.js I'm trying to export a class and then use another file within my App.js which is inside the somePage() function. where I'm calling <Header/> in an attempt for that text to appear on my physical device upon hitting refresh.
It displays <Login/> perfectly, but not what's within the somePage() function. My question is, why?
(I'm using Expo by the way, instead of having an index.ios.js file it's an App.js file that still supports cross platform development).
Here's my App.js file:
import React, { Component } from 'react';
import {AppRegistry} from 'react-native';
import Login from './components/Login';
import Header from './components/Header';
export default class Project extends Component {
render() {
return (
<Login/>
);
}
}
const somePage = () => (
<Header/>
);
AppRegistry.registerComponent('someProject', () => Project);
AppRegistry.registerComponent('someProject', () => somePage);
Here's my Header.js file:
import React from 'react';
import {Text} from 'react-native';
const Header = () => {
return <Text>Testing this out</Text>
}
export default Header;
The concept of react is that a parent component renders child components. You only need to register once because the root component is the parent component of all other components. Any other child or grandchild components you want to render must be descendants of the root component. As a side note, you don't need to have export default in front of the Project component, because you aren't exporting it anywhere: you are registering it below.
To fix your app, you need to place the header component inside the registered root component:
import React, { Component } from 'react';
import {AppRegistry, View } from 'react-native';
import Login from './components/Login';
import Header from './components/Header';
class Project extends Component {
render() {
return (
<View>
<Header/>
<Login/>
</View>
);
}
}
AppRegistry.registerComponent('someProject', () => Project);