this the first time to me with context in Reactjs and have this problem Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports. Check the render method of App `
FeedbackContext.js
import React from "react"; const defaultValue = { uid: null, title: null, appName: null, type: null, feedbackDescription: null, } const FeedbackContext = React.createContext({ selectedFeedback: defaultValue, updateSelectedFeedback: () => {} }); export default FeedbackContext ;
App.js
import React from "react"; import './App.css'; import MainNav from "./componets/Navbar/MainNav"; import firebase from './config/fbConfig'; import RoutersContainer from "./AppRouters/RoutersContainer"; import FeedbackContext from "./contextApi/FeedbackContext"; class App extends React.Component { constructor(props) { super(props); this.state = { userType: 'undefined', selectedFeedback: { uid: null, title: null, appName: null, type: null, feedbackDescription: null, } } } componentDidMount() { firebase.auth().onAuthStateChanged(user => { if (user) { this.setState({userType: 'login'}) } else { this.setState({userType: 'logout'}) } }) } updateSelectedFeedback = (feedback) => { this.setState({selectedFeedback: feedback}) } render() { return ( <FeedbackContext.provider value={{ selectedFeedback: this.state.selectedFeedback, updateSelectedFeedback: this.updateSelectedFeedback }}> <div className="App"> <MainNav userType={this.state.userType}/> <RoutersContainer userType={this.state.userType}/> {/*this button only on test mode*/} <button onClick={() => { { if (this.state.userType === 'admin') { this.setState({userType: "login"}) } else if (this.state.userType === 'login') { this.setState({userType: "admin"}) } } }} > he is {this.state.userType} </button> </div> </FeedbackContext.provider> ); } } export default App
ShowButton.js
import React from "react"; import FeedbackContext from "../../contextApi/FeedbackContext"; class ShowButton extends React.Component { render() { return ( <FeedbackContext.consumer> {({updateSelectedFeedback ,selectedFeedback }) => <> <button onClick={updateSelectedFeedback(this.props.feedback)}>Show</button> {console.log(selectedFeedback)} </>} </FeedbackContext.consumer> ) } } export default ShowButton
Advertisement
Answer
It’s consumer should be capital.
//.... render() { return ( <FeedbackContext.Consumer> {({updateSelectedFeedback ,selectedFeedback }) => <> <button onClick={updateSelectedFeedback(this.props.feedback)}>Show</button> {console.log(selectedFeedback)} </>} </FeedbackContext.Consumer> ) } }