How can I get the current refinement *count* using Algolia? - reactjs

React InstantSearch provides a CurrentRefinements component which gives the currently selected refinements.
But all I want is to get the number of filters (refinements) being applied. I feel like this should be really easy but have been banging my head for the past 4 hours trying to figure it out.
Edit: You can see a working example with <CurrentRefinements> here
But again, my goal isn't to list the current refinements, it's to get a count of the number of refinements being applied in total.

I got it working using one of the connectors they provide. Here's the solution:
import React, {Component} from 'react'
import {connectCurrentRefinements} from 'react-instantsearch/connectors'
class RefinementCount extends Component {
render() {
return (
<h1>filtered: {this.props.items.length}</h1>
)
}
}
export default connectCurrentRefinements(RefinementCount)
Relevants docs: https://community.algolia.com/react-instantsearch/connectors/connectCurrentRefinements.html

Related

how can i manage the sate of my project i want to use redux for that but on class based compoennts

i want to use redux to manage the state of my application i know it is very easy to do this with function based compoenents because we have the useDispatch and useSelector but in the case of class based component we have what after struggling a lot of research i manage to find this super demo project which explain how we can use the state management in the class based compoents but when i go to use that they have used this createStore import { createStore } from "redux"; which using i am getting error that createStore has been deprecated just see the error below line
#deprecated
We recommend using the configureStore method of the #reduxjs/toolkit package, which replaces createStore.
Redux Toolkit is our recommended approach for writing Redux logic today, including store setup, reducers, data fetching, and more.
For more details, please read this Redux docs page: https://redux.js.org/introduction/why-rtk-is-redux-today
I visited that place link but probably i am lost please help show me that way i want to state management smoothly its ok if i write more code but i want to do it i am bound to use class based component because i am writing a test
-----------------------------------------------------------------------------------------
Now i am able to do the global state but still wondering how we can read the data and show it in our UI i have tried useSelector in all possible ways can anyone suggest me how can i do that
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { increment,decrement } from '../features/counterSlice'
import { useSelector } from 'react-redux'
export class ClassTest extends Component {
constructor(props){
super(props)
console.log("the props are",this.props)
}
increase(){
this.props.increment();
console.log("Hello")
}
decrease(){
this.props.decrement();
console.log("Hello")
}
componentDidMount(){
const count = this.props.useSelector()
console.log(count)
}
render() {
return (
<div>
<button onClick={()=>{this.increase()}}>Increase Me</button>
<button onClick={()=>{this.decrease()}}>Increase Me</button>
</div>
)
}
}
export default connect(null,{increment,decrement,useSelector}) (ClassTest);
Generally, you really should not start a class-based project in 2022. They are essentially a legacy feature of React - the ecosystem has moved on, new library have little to none support for them. You will find yourself in a deadlock, not being able to use any modern libraries if you continue with class components.
That said, also Redux has moved on. While it supports class components all the same as before (connect is the only part of react-redux that interacts with your classes and that has not changed), the way how Redux code itself is written has changed massively in the last few years and modern Redux code as a consequence is 1/4 of the code it used to be, with much more security against bugs.
But that also means that most old tutorials and example projects are completely outdated and should not be used for learning any more. The one you have there certainly is one of those, since it uses createStore which you should not be using any more since 2019 if you were following official recommendations.
Please take a step back and evaluate if you really want to use class components.
Apart from that, please follow the official Redux tutorial instead of trying to run random outdated boilerplates from the internet.

thinking in react with different example?

I have seen the thinking in react article found here and in short it discusses how to break down components...
while i understand the concept in their example and it looks like this..
each colored box must be a separate component...
now I am creating a login page and i am a bit confused on how to break it down as most of it will not be reused somewhere else and i started to mix multiple concepts together I am wondering if you guys can help me sort my thoughts about this topic
screen shot of similar login page to the one i am making i have already colored components that should be separated based on the react official page docs so please let me know if I am thinking correctly and if any extra tips would be appreciated
React basically is component based library which is re-usable in projects.
For Example you can create the file InputComponent.js :
import React from 'react'
function InputComponent() {
const [name , setName] = React.useState('')
return (
<input placeholder="Name" onChange={(e)=>setName(e.target.value)} type="text" ></input>
)
}
export default InputComponent;
And use it anywhere as many as you want like this :
import React from 'react'
function Home() {
return (
<div>
<InputComponent></InputComponent>
<InputComponent></InputComponent>
</div>
)
}
export default Home
The more re-useable components you can define your project will be more readable and easy foremost .
You can make a re-usable component from anything you desire like some text , input elements and etc ...
You can use component props to pass in any information to the re-usable component to display that information .
For more info you can check the react docs here .

How to Display Wiki Page in HTML using React

so my goal is to display a Page from Wikipedia in my Web-Page using React. I have only one Idea to do that, and it's:
First Step: Export data from Wiki as .XML
Second Step: import data from .xml in HTML(using React).
First Step I have done succesfully, but I have Problems with second.
I have found xml-parser from npm(xml-loader):https://www.npmjs.com/package/xml-loader. but it's giving me only following string: "/static/media/wiki.c6730c07.xml" . Knows someone better way to do that, or it will be good if you say, that I am on right way. My code in React is :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
var wiki = require('./wiki.xml');
class App extends Component {
render() {
return (
<div className="App">
{wiki}
</div>
);
}
}
export default App;
xml-renderer might be a good candidate for helping you.
So, I have found out that, to do something like this, I have to use "xslt", where I can get data from ".xml" and display them how I want. Important is to create a reference between xml and xslt. Here are tree links, where you can see it on example:
https://www.youtube.com/watch?v=Zn9A5k23Oto
https://www.youtube.com/watch?v=Icg0Su5uEa8
https://www.codeproject.com/Articles/12047/How-to-Convert-XML-Files-to-HTML
But last question is: I want to display data from Wiki exactly how it is on it's Page, Is this Possible ?
If someone knows answer, please write Hint.
Regarding to your second question, about how to display data from Wiki exactly how it is on it's Page, you can use the <iframe> tag.
You can find more information here.

How do you organise actions in Redux?

I have a folder called actions with a file called index.js, and I have been putting all my actions into it so far. It's getting quite messy now and I was wondering how to best split things. Is there any good strategy? Do you keep them in different files? Grouped by...? Or do you just keep them in different files as partials and then include them in the index file, and then always only ever import the index file?
Putting everything in one action.js will very quickly grow out of control, the same is the case for the reducers.
It really comes down to personal taste, but the trends i've seen, seems to be to seperate the app into features, where each feature is isolated with its own actions, and a reducer for each feature as well.
Each level of the application tree will then combine reducers and your store will end up looking like the folder-structure, making it easier to find things. A feature will typically contain actions.js, reducer,js, index.jsx and maybe also style.scss/css for that feature. The pros of doing it that way, is that it is extremely easy to remove the feature at some point, without having to dig for dead code all over the place.
You don't mention how you bundle your code. This approach is nice when building with ex Webpack.
You can use bindActionCreators (http://redux.js.org/docs/api/bindActionCreators.html).
Small example:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as filterActions from '../actions/filterActions';
import * as writeActions from '../actions/writeActions';
class TestComponent extends Component {
render(){
return <div>Test</div>;
}
}
function mapDispatchToProps(dispatch){
return {
filterActions: bindActionCreators(filterActions, dispatch),
writeActions: bindActionCreators(writeActions, dispatch)
};
}
export default connect(null, mapDispatchToProps)(TestComponent);
This will add the actions to the props of your component (at the key that you used in the return Object in mapDispatchToProps). So if you want to use an action from filterActions you can use this.props.filterActions.actionName().

How to import a component or file in React using variables?

I'm building a web app using React that shows the blueprint for the building you select, in an already selected campus.
I have a "Content" component that loads the campus or building map, depending what you chose.
The "BuildingMap" component needs to load a specific blueprint according to what building you selected. It gets the props.building with the name of the building but I don't know how to load a component using that variable.
I have tried import, fetch and require but nothing seems to work.
Please help.
My code looks something like this:
//Content Component
<BuildingMap building={selectedBuilding} campus={selectedCampus} />
//BuildingMap Component
import *MyBlueprint* from (specific folder depending on the campus selected)
class BuildingMap extends React.Component {
render(){
return (
<div className="blueprint" id={this.props.building}>
{*MyBlueprint*}
</div>
)
}
}
Unfortunately, you cannot import/require components dynamically in React environment.
Depending on how many buildings/blueprints there are, it's possible to import them one by one, create component-building map and pick component by building ID.
If there are many/infinite components to load, I would surely pick another method - don't know content of your problem.
import BlueprintA from './BlueprintA'
import BlueprintB from './BlueprintB'
import BlueprintC from './BlueprintC'
// ...
class BuildingMap extends React.Component {
render(){
const C = {
buildingA: BlueprintA,
buildingB: BlueprintB,
buildingC: BlueprintC,
// ...
}[this.props.building]
return (
<div className="blueprint" id={this.props.building}>
<C />
</div>
)
}
}
This question is pretty old but as I was looking for how to solve the same problem let me give my answer. It can be done with dynamic import React.lazy:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
See more details here: https://reactjs.org/docs/code-splitting.html#reactlazy
To add to #Andreyco's answer:
Using a lookup table of string IDs/names to component classes is a typical React idiom. One common use case is a modal manager component that can render multiple different types of modals. For some examples, see Dan Abramov's answer at "How can I render a modal dialog in Redux?" (not Redux-specific), as well as some of the related articles in the React Component Patterns#Modal Dialogs and Redux Techniques#UI sections of my React/Redux links list.
Per #azium's comment: it is definitely possible to use dynamic importing (via require.ensure() or the new import() function) to load chunks at runtime, and you could add the exports from those dynamically imported chunks into a lookup table when they are loaded.

Resources