Could you please help use to resolve this case
Parent component
const HelloMessage = (props) => {
return <>
<div className="main-counter" >
<top-destination name="srini" />
</div>
</>
}
export default HelloMessage
customElements.define("react-counter", reactToWebComponent(HelloMessage, React, ReactDOM));
Child (Web component)
import React from 'react';
import reactToWebComponent from "react-to-webcomponent";
const TopDestination = (props) => {
console.log(props);
return <>
<div>{props.name}</div>
</>
}
export default TopDestination
customElements.define("top-destination", reactToWebComponent(TopDestination, React, ReactDOM));
console log value
In html
<top-destination name="John" />
Cross-check your Node version, It should be Node 14 or above.
Cross-check your import ReactDom statement, based on the React version you are using.
Update to the latest version of react-to-webcomponent and prop-types
Your code should be like this:
Parent component
import React from 'react';
const HelloMessage = (props) => {
return <>
<div className="main-counter" >
<top-destination name="srini" />
</div>
</>
}
export default HelloMessage
customElements.define("react-counter", reactToWebComponent(HelloMessage, React, ReactDOM));
Child (Web component)
import React from 'react';
import PropTypes from "prop-types"
import * as ReactDOM from 'react-dom/client';
import reactToWebComponent from "react-to-webcomponent"
const TopDestination = (props) => {
console.log(props);
return <>
<div>{props.name}</div>
</>
}
TopDestination.propTypes = {
name: PropTypes.string,
}
customElements.define("top-destination", reactToWebComponent(TopDestination, React, ReactDOM));
export default TopDestination
// Other ways of defining the props if you are on better versions.
// customElements.define(
// "top-destination",
// reactToWebComponent(TopDestination, React, ReactDOM, {
// props: {
// name: String
// },
// }),
// )
// or
// customElements.define(
// "top-destination",
// reactToWebComponent(TopDestination, React, ReactDOM, {
// props: ["name"]
// }),
// )
Refer this repo: https://github.com/sarat9/cross-ui-web-comp
File: https://github.com/sarat9/cross-ui-web-comp/blob/master/react-web-components/src/web-components/FancyButtonWC.js
Related
Hey all im looking for help. im having some trouble with passing data from one child component to another child component using the context api. But i get this typeError instead, i tried a few searches so far without much luck. if anyone can't point me in the right direction it would be much appreciated!
thanks
CurrencyProvider.js
import { React, Component} from 'react';
export const MContext = React.createContext('');
class CurrencyProvider extends Component {
constructor() {
super()
this.state = {
setinputValue: (value) => this.setState({ inputValue: value })
}
}
render() {
return (
<MContext.Provider value={this.state}>
{this.props.children}
</MContext.Provider>)
}
}
export default CurrencyProvider;
Dropdown.js
import { useQuery, gql } from "#apollo/client";
import { useState } from "react";
import './Dropdown.scss';
import { MContext } from "../CurrencyProvider";
const EXCHANGE_RATES = gql`
query GetExchangeRates {
rates(currency: "AUD") {
currency
rate
name
}
}
`;
function Dropdown() {
const [isToggled, setToggle] = useState(false);
const { data, loading, error } = useQuery(EXCHANGE_RATES);
if (loading) {
return <div>loading</div>;
}
if (error) {
return <div>{error}</div>;
}
return (
<div className="custom-dropdown">
<ul className={`dropdown-menu ${isToggled ? 'open':''}`}>
<li value="0" className="first-item" onClick={() => setToggle(!isToggled)} onKeyPress={() => setToggle(!isToggled)} tabIndex="0">Select Currency:</li>
{data.rates.map(({ currency, rate, name },index) => (
<MContext.Consumer>
{(context) => (
<li className="list-item" key={index} data={rate} tabIndex="0" onClick={()=>{context.setinputValue(rate)}}> <span>{name}: {currency}</span></li>
)}
</MContext.Consumer>
))}
</ul>
</div>
);
}
export default Dropdown;
Input.js
import './Input.scss';
import { MContext } from "../CurrencyProvider";
function Input() {
return(
<MContext.Consumer>
{(context) => (
<input value={context.state.inputValue} />
)}
</MContext.Consumer>
);
}
export default Input;
CurrencyContainer.js
import Dropdown from '../Dropdown/Dropdown';
import Input from '../Input/Input';
import './CurrencyContainer.scss';
import CurrencyProvider from '../CurrencyProvider';
function CurrencyContainer() {
return (
<div className='currency-container'>
<h1 >Select Items</h1>
<div className="currency-wrapper">
<CurrencyProvider>
<div><Input /></div>
<div><Dropdown /></div>
<div><Dropdown /></div>
</CurrencyProvider>
</div>
</div>
);
}
export default CurrencyContainer;
App.js
import logo from './logo.svg';
import './App.scss';
import { client } from "./ApolloClient/client";
import { ApolloProvider } from '#apollo/client';
import CurrencyContainer from './CurrencyContainer/CurrencyContainer';
function App() {
return (
<ApolloProvider client={client}>
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
<CurrencyContainer />
</div>
</ApolloProvider>
);
}
export default App;
Why don't you try placing something more in the likes of this in a separate file mcontext.context.jsx:
import { createContext } from "react";
const MContext = createContext('');
export default MContext;
Then you can import it and
get values by importing your newly created context, the useContext hook and adding something like this to the top of a functional component which is encapsulated inside a MContext.Provider node:
const val = useContext(MContext);
set values:
<MContext.Provider value={mcontextValue}>
</MContext.Provider>
All children inside your MContext.Provider node and their children will have access to your MContext value given you get it as I showed you in the 1st part of the answer.
Your React import is incorrect. Change it to:
import React, {Component} from 'react';
React is the default export, not a named export.
React package doesn't have a named import called React, it has a default import that people generally use React for, so you should change this line
import { React, Component } from 'react';
to this
import React, { Component } from 'react';
If you use React 17+, you don't need to import React from 'react'; anymore, you can remove any mentioning of React from your import, so your import will look like this
import { createContext } from 'react';
But you have to turn off the lint rules for this import in your .eslintrc.json file like so
{
"rules": {
...
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off"
}
}
I want to repeat my component for n times using react in ionic but i don't know how to that
for example in my Component.tsx i have:
import React from 'react';
import { IonCard, IonCardContent} from '#ionic/react';
const Component: React.FC = () => {
return(
<div>
<IonCard>
<IonCardContent>Hello From Ion Card</IonCardContent>
</IonCard>
</div>
)
};
export default Component;
And in my App.tsx I have:
import { IonApp} from '#ionic/react';
import '#ionic/react/css/core.css';
import '#ionic/react/css/normalize.css';
import '#ionic/react/css/structure.css';
import '#ionic/react/css/typography.css';
import '#ionic/react/css/padding.css';
import '#ionic/react/css/float-elements.css';
import '#ionic/react/css/text-alignment.css';
import '#ionic/react/css/text-transformation.css';
import '#ionic/react/css/flex-utils.css';
import '#ionic/react/css/display.css';
import './theme/variables.css';
import Component from './Component';
const App: React.FC = () => (
<IonApp className="ion">
<div>
{
// I want to repeat this
<Component />
}
</div>
</IonApp>
);
export default App;
I'm new to typescript and react, I would be so happy if you help
Thanks
You need a loop. The best loop here is map:
const App: React.FC = () => (
<IonApp className="ion">
<div>
{
Array(5).fill(null).map((_, i) => (
<Component key={i} />
))
}
</div>
</IonApp>
);
Don't forget that repeated components need to have a unique key prop in the loop.
And please pay attention to .fill(null). When you create an array using the Array function, it gets filled with empty values, and running .map method on it will fail. We have to fill it with a value (In this case null) in order to make it iterable.
I'm new to React and I'm trying to use Context API. Here is my code:
FormColorContext.js
import React, { useState } from 'react';
export const FormColorContext = React.createContext();
const FormColorProvider = (props) => {
const [color, setColor] = useState('white')
return (
<FormColorContext.Provider value={{color}}>
{props.children}
</FormColorContext.Provider>
)
}
export default FormColorProvider
dashboard.js
import React from 'react';
import FormColorProvider from '../context/FormColorContext';
import DefaultLayout from '../layout/default-layout';
import EmptyDashboardComponent from '../components/Dashboard/EmptyDashboardComponent';
import NewFormComponent from '../components/Dashboard/NewFormComponent';
import ColorSelectorComponent from '../components/Dashboard/ColorSelectorComponent';
import styles from '../styles/dashboard.module.css';
export default function Dashboard() {
return (
<div>
<DefaultLayout>
<div className={styles.containerMain}>
<h1 className={styles.headingCenter}>Create a new form</h1>
<FormColorProvider>
<ColorSelectorComponent/>
<NewFormComponent/>
</FormColorProvider>
</div>
</DefaultLayout>
</div>
)
}
NewFormComponent.js
import React, { useContext } from 'react';
import styles from '../../styles/NewFormComponent.module.css';
import FormColorContext from '../../context/FormColorContext';
export default function NewFormComponent() {
const color = useContext(FormColorContext);
console.log(color);
return (
<div className={styles.formContainer}>
</div>
)
}
I made sure that all imports are correct, but for some reason when I try to log color variable I'm getting undefined. What am I doing wrong? Thanks in advance.
Renato
Sample Example: Expo Snack
In your Context Provider you are passing an object, so access color like below:
NewFormComponent.js:
import React, { useContext } from 'react';
import styles from '../../styles/NewFormComponent.module.css';
import {FormColorContext} from '../../context/FormColorContext';
export default function NewFormComponent() {
const {color} = useContext(FormColorContext);
console.log(color);
return (
<div className={styles.formContainer}>
</div>
)
}
FormColorContext.js:
import React, { useState } from 'react';
export const FormColorContext = React.createContext();
export const FormColorProvider = (props) => {
const [color, setColor] = useState('white')
return (
<FormColorContext.Provider value={{color}}>
{props.children}
</FormColorContext.Provider>
)
}
** dashboard.js: **
import React from 'react';
import {FormColorProvider} from '../context/FormColorContext';
import DefaultLayout from '../layout/default-layout';
import EmptyDashboardComponent from '../components/Dashboard/EmptyDashboardComponent';
import NewFormComponent from '../components/Dashboard/NewFormComponent';
import ColorSelectorComponent from '../components/Dashboard/ColorSelectorComponent';
import styles from '../styles/dashboard.module.css';
export default function Dashboard() {
return (
<div>
<DefaultLayout>
<div className={styles.containerMain}>
<h1 className={styles.headingCenter}>Create a new form</h1>
<FormColorProvider>
<ColorSelectorComponent/>
<NewFormComponent/>
</FormColorProvider>
</div>
</DefaultLayout>
</div>
)
}
The problem is in imports. You import the default value in NewFormComponent.js file. Change the import to import {FormColorContext} from '../../context/FormColorContext';
Moreover, it is a dupliate of useContext() returns undefined
you could have googled it)
You have a problem in importing the FormColorContext in your NewFormComponent and it's passing the undefined to useContext method and it returns undefined too.
here is what you need to do:
import React, { useContext } from 'react';
import styles from '../../styles/NewFormComponent.module.css';
import FormColorContext from '../context/FormColorContext';
export default function NewFormComponent() {
// remember to destructure the color variable
const { color } = useContext(FormColorContext);
console.log(color);
return (
<div className={styles.formContainer}>
</div>
)
}
I'm a bit confused about redux implementation.
Let's say my app has this component structure:
-App
--ProfilationStep
---ProfilationStep1
----React-Select (http://jedwatson.github.io/react-select/)
I need to use redux because the app is going to grow bigger and deeper, so I started by setting up Actions, Reducers and Action types for the React-Select component. I also set the mapStateToProps in the App.js file.
Now I need to know how to pass/access the data stored in redux to other components (React-Select for example) and how to edit it with the actions I declared.
This is my index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import ProfilationSelectReducer from './components/reducers/profilationSelect';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const store = createStore(
ProfilationSelectReducer
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
registerServiceWorker();
This is my App.js
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { bindActionCreators} from 'redux'
import Profilation from './components/Profilation'
import ProfilationStep from './components/Profilation/ProfilationStep'
import { connect } from 'react-redux';
import * as SelectActionCreators from './components/actions/profilationSelect'
import 'react-select/dist/react-select.css';
class App extends Component {
static propTypes = {
steps: PropTypes.array.isRequired
};
render() {
console.log(this.props)
const { dispatch, steps } = this.props;
const changeValue= bindActionCreators(SelectActionCreators.changeValue, dispatch);
const stepComponents = this.props.steps.map((step, index) => (
<ProfilationStep
key={index}
index={index}
step={step}
/>
));
return (
<div className="repower-app">
{ stepComponents }
</div>
);
}
}
const mapStateToProps = state => ({
steps:state.steps
});
export default connect(mapStateToProps)(App);
This is my ProfilationStep.js file
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import ProfilationStep1 from './ProfilationStep1'
import ProfilationStep2 from './ProfilationStep2'
import ProfilationStep3 from './ProfilationStep3'
import ProfilationStep4 from './ProfilationStep4'
import ProfilationStep5 from './ProfilationStep5'
const ProfilationStep = props =>
<div className='ProfilationStep'>
{props.index===0 &&
<ProfilationStep1
step={props.step}
/>
}
{props.stepIndex===2 &&
<ProfilationStep2
handleSelect={props.handleSelect}
handleInput={props.handleInput}
expend={props.expend}
period={props.period}
light={props.light}
gas={props.gas}
/>
}
{props.stepIndex===3 &&
<ProfilationStep3
handleSelect={props.handleSelect}
environment={props.environment}
/>
}
{props.stepIndex===4 &&
<ProfilationStep4
flexibility={props.flexibility}
handleSelect={props.handleSelect}
/>
}
{props.stepIndex===5 &&
<ProfilationStep5
customize={props.customize}
handleSelect={props.handleSelect}
/>
}
</div>
export default ProfilationStep
This is my ProfilationStep1.js file
import React, { Component } from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types'
var jobOptions = [
{ value: 'edilizia', label: 'Edilizia' },
{ value: 'editoria', label: 'Editoria' },
{ value: 'educazione', label: 'Educazione' }
];
const ProfilationStep1 = props =>
<div className='ProfilationStep'>
La mia attività si occupa di <Select
name="job"
value={props.step.job}
onChange={e => props.changeValue(e.target.value)}
options={jobOptions}
/>
</div>
ProfilationStep1.propTypes = {
//isComplete: PropTypes.bool.isRequired,
//isActive: PropTypes.bool.isRequired
job: PropTypes.string.isRequired,
service: PropTypes.string.isRequired,
handleSelect: PropTypes.func.isRequired
}
export default ProfilationStep1
This is my reducer
import * as ProfilationSelectActionTypes from '../actiontypes/profilationSelect';
const initialState = {
steps: [{
job: "",
service: ""
}],
}
export default function ProfilationSelectReducer (state=initialState, action){
switch(action.type){
case ProfilationSelectActionTypes.CHANGE_VALUE:
return {
...state,
steps:[{
job: action.value
}]
};
default:
return state;
}
}
This is my actiontypes file
export const CHANGE_VALUE ='profilationSelect/CHANGE_VALUE';
and, finally, this is my actions file
import * as ProfilationSelectActionTypes from '../actiontypes/profilationSelect';
export const changeValue = value =>{
return{
type: ProfilationSelectActionTypes.CHANGE_VALUE,
value
}
}
Thank you for any help
You are definitely on the right way.
The solution is simple: You bind your state to the react props. With the props, you can do whatever you like (e.g. pass them to react-select). If you want to modify it, you have to map "mapDispatchToProps", where you map functions, which execute your actions to the props. This works the same as "mapStateTopProps":
End of App.js (import your actions file on top, named "profilationSelectActions" here):
const mapStateToProps = state => ({
steps:state.steps
});
const mapDispatchToProps = dispatch => ({
updateJobValue: (value) => dispatch(profilationSelectActions.changeValue(value))
}
// Also add here mapDispatchToProps
export default connect(mapStateToProps, mapDispatchToProps)(App);
Now the function "updateJobValue" is available in the props of your app.js. You can now easily pass it down to your components and to the onChange event of react-select:
In your ProfilationStep1.js change this line:
onChange={e => props.changeValue(e.target.value)}
To this (after you passed the function updateJobValue down)
onChange{e => props.updateJobType(e.target.value)}
After that, updateJobType should go all the way up to App.js and then dispatch the action. After that, the application will re-render with the new steps.
Hi i am quite new to react and redux , i was creating a poc and got this error , despite my efforts i am not able to solve this
here is my code
shoping-app/app/index.jsx
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import reducer from './reducers/index.js'
import {Provider} from 'react-redux'
let store = createStore(reducer)
import App from './components/App'
ReactDOM.render(
<Provider store={store}><App/></Provider>,document.getElementById('app'));
shoping-app/app/components/product.jsx
import React from 'react'
let Product =({id,name,cost,handleClick})=>{
<div>
{name} ${cost}<button onClick={()=>handleClick(id)}>Add to Cart</button>
</div>
}
export default Product
shoping-app/app/components/App.jsx
import React, { Component } from 'react'
import Products from '../containers/products.jsx'
export default class App extends Component {
render(){
return (
<div>
<p>Welcome to our shop</p>
<Products/>
</div>
)
}
}
shoping-app/app/components/products.jsx
import React from 'react'
import Product from './product.jsx'
let Products=({products,handleClick})=>(
<section>
<h2>Our Products</h2>
< section>
{products.map(product=><Product
key={product.id}
{...product}
handleClick={handleClick}/>)}
</section>
</section>
)
export default Products
shoping-app/app/containers/products.jsx
import React from 'react'
import {connect} from 'react-redux'
import Products from '../components/products.jsx'
function mapStateToProps(state){
return{
products:state.products
}
}
function mapDispatchToProps(dispatch){
return{
handleClick(id){
dispatch({
type:'ADD_TO_CART',
payload:{
id
}
})
}
}
}
let ProductsContainer =connect(mapStateToProps,mapDispatchToProps) (Products)
export default ProductsContainer
shoping-app/app/reducers/index.js
import {ADD_TO_CART,REMOVE_FROM_CART,CHANGE_CATEGORY} from '../constants/actionTypes'
let initialState={
activeCategory:'food',
products:[
{id:193,name:'pizza',cost:10},
{id:194,name:'pizza2',cost:100},
{id:195,name:'pizza3',cost:1000},
{id:196,name:'pizza4',cost:10000},
],
shoppingCart:[]
}
export default function reducer(state=initialState,action){
switch(action.Type){
case CHANGE_CATEGORY:
return{
...state,
activeCategory:action.payload
}
case ADD_TO_CART:
return{
...state,
shoppingCart:[...state.shoppingCart,action.payload]
}
case REMOVE_FROM_CART:
return{
...state,
shoppingCart:state.shoppingCart.filter(productId=>productId!=action.payload)
}
default:
return state
}
}
The problem is this : shoping-app/app/components/product.jsx
The default exported function of this just references a react component but it does not return anything. In order to return you have to type return keyword explicitly or just wrap your object(the component in this case) in parentheses ().
import React from 'react'
let Product =({id,name,cost,handleClick})=> ({
<div>
{name} ${cost}<button onClick={()=>handleClick(id)}>Add to Cart</button>
</div>
})
export default Product
For a start change this error in your code.
ReactDOM.render(
<Provider store={store}><App/></Provider>,document.getElementById('app'));
to
const elem = () => <Provider store={store}> <App/> </Provider>;
ReactDOM.render(elem, document.getElementById('app'));
After that change the curly braces inside your product.jsx to parenthesis like so.
let Product =({id,name,cost,handleClick}) => (
//
//
)
This way, you'll be returning a valid jsx from Product. By enclosing it in curly braces, you simply start the function definition but return nothing.